JDBC is now on GBorg

This commit is contained in:
PostgreSQL Daemon 2004-01-19 20:07:14 +00:00
parent 9bd681a522
commit 2a9bf5b33d
147 changed files with 0 additions and 33298 deletions

View File

@ -1,44 +0,0 @@
#-------------------------------------------------------------------------
#
# Makefile for JDBC driver
#
# Copyright (c) 2001, PostgreSQL Global Development Group
#
# $PostgreSQL: pgsql/src/interfaces/jdbc/Makefile,v 1.39 2003/11/29 19:52:09 pgsql Exp $
#
#-------------------------------------------------------------------------
subdir = src/interfaces/jdbc
top_builddir = ../../..
include $(top_builddir)/src/Makefile.global
majorversion:= $(shell echo $(VERSION) | sed 's/^\([0-9][0-9]*\)\..*$$/\1/')
minorversion:= $(shell echo $(VERSION) | sed 's/^[0-9][0-9]*\.\([0-9][0-9]*\).*$$/\1/')
build.properties: $(top_builddir)/src/Makefile.global
@echo "# This file was created by 'make build.properties'." > build.properties
@echo major=$(majorversion) >> build.properties
@echo minor=$(minorversion) >> build.properties
@echo fullversion=$(VERSION) >> build.properties
@echo def_pgport=$(DEF_PGPORT) >> build.properties
@echo enable_debug=$(enable_debug) >> build.properties
all: build.properties
$(ANT) -buildfile $(srcdir)/build.xml all
install: installdirs build.properties
$(ANT) -buildfile $(srcdir)/build.xml install \
-Dinstall.directory=$(javadir)
installdirs:
$(mkinstalldirs) $(javadir)
uninstall:
$(ANT) -buildfile $(srcdir)/build.xml uninstall \
-Dinstall.directory=$(javadir)
clean distclean maintainer-clean:
$(ANT) -buildfile $(srcdir)/build.xml clean_all
check: build.properties
$(ANT) -buildfile $(srcdir)/build.xml test

View File

@ -1,226 +0,0 @@
This is a simple readme describing how to compile and use the jdbc driver.
---------------------------------------------------------------------------
This isn't a guide on how to use JDBC - for that refer to sun's web site:
http://java.sun.com/
For problems with this driver, then refer to the postgres-jdbc email
list:
http://www.postgresql.org/
The Driver's home page is:
http://jdbc.postgresql.org/
---------------------------------------------------------------------------
COMPILING
To compile you will need to have ANT installed. To obtain ant go to
http://jakarta.apache.org/ant/index.html and download the binary. Being pure
java it will run on virtually all java platforms. If you have any problems
please email the jdbc list.
Once you have ANT, run the configure script in the top-level directory with
the --with-java option. Then proceed with 'make' and 'make install' as
usual. This will compile the correct driver for your JVM, and build a .jar
file (Java ARchive) called postgresql.jar. The file will be installed in
the directory PREFIX/share/java.
That jar file will contain the driver for _your_ version of the JDK.
If you would like to use ANT directly, first invoke 'make build.properties'
after running the configure script with the java option. This will create a
needed Java properties file from the configured information.
REMEMBER: Once you have compiled the driver, it will work on ALL platforms
that support that version of the API. You don't need to build it for each
platform.
Possible problems
You may see a message similar to:
postgresql/Driver.java:87: interface java.sql.Connection is an interface. It can't be instantiated.
return new Connection (host(), port(), props, database(), url, this);
This is caused by not having the current directory in your CLASSPATH. Under
Linux/Solaris, unset the CLASSPATH environment variable, and rerun ant.
If you are still having problems, prebuilt versions of the driver
are available at http://jdbc.postgresql.org/
---------------------------------------------------------------------------
INSTALLING THE DRIVER
To install the driver, the .class files have to be in the classpath.
ie: under LINUX/SOLARIS (the example here is my linux box):
export CLASSPATH=.:/usr/local/pgsql/share/java/postgresql.jar
---------------------------------------------------------------------------
USING THE DRIVER
To use the driver, you must introduce it to JDBC. Again, there's two ways
of doing this:
1: Hardcoded.
This method hardcodes your driver into your application/applet. You
introduce the driver using the following snippet of code:
try {
Class.forName("org.postgresql.Driver");
} catch(Exception e) {
// your error handling code goes here
}
Remember, this method restricts your code to just the postgresql database.
However, this is how most people load the driver.
2: Parameters
This method specifies the driver from the command line. When running the
application, you specify the driver using the option:
-Djdbc.drivers=org.postgresql.Driver
eg: This is an example of running one of my other projects with the driver:
java -Djdbc.drivers=org.postgresql.Driver uk.org.retep.finder.Main
note: This method only works with Applications (not for Applets).
However, the application is not tied to one driver, so if you needed
to switch databases (why I don't know ;-) ), you don't need to
recompile the application (as long as you havent hardcoded the url's).
---------------------------------------------------------------------------
JDBC URL syntax
The driver recognises JDBC URL's of the form:
jdbc:postgresql:database
jdbc:postgresql://host/database
jdbc:postgresql://host:port/database
Also, you can supply both username and passwords as arguments, by appending
them to the URL. eg:
jdbc:postgresql:database?user=me
jdbc:postgresql:database?user=me&password=mypass
Notes:
1) If you are connecting to localhost or 127.0.0.1 you can leave it out of the
URL. ie: jdbc:postgresql://localhost/mydb can be replaced with
jdbc:postgresql:mydb
2) The port defaults to 5432 if it's left out.
---------------------------------------------------------------------------
That's the basics related to this driver. You'll need to read the JDBC Docs
on how to use it. However, there are some examples included in the example
directory. To build, type: make examples
To run them, they follow the same syntax. For example, the basic example shows
how to insert data, and perform queries:
java example.basic jdbc:postgresql:test user password
---------------------------------------------------------------------------
POSTGRESQL SPECIFICS
--------------------
Large Objects:
A "feature" of PostgreSQL is that access to LargeObjects is only permitted
within a Transaction. Because of this, any use of LargeObjects (also known
as Blobs) requires that the Connection.setAutoCommit() method be called
disabling the autocommit feature.
For example:
Connection db; // open the connection here
db.setAutoCommit(false); // Turn off AutoCommit
------------------
Large Object API
The first thing you need to do is to open the LargeObjectManager. This class
handles the opening of existing objects, and creating new ones. To do this,
you use the following line of code:
LargeObjectManager lobj;
lobj = ((org.postgresql.Connection)db).getLargeObjectAPI();
where db is a reference to an open Connection object.
Once that is done, you can use the API for the lifetime of that Connection.
To create an object, you call the create() method. This takes an argument
with the file modes you intend to use. The following line is normally
sufficient:
int oid = lobj.create(LargeObjectManager.READ|LargeObjectManager.WRITE);
Here, lobj is the LargeObjectManager we have opened earlier, and oid is the
Large Object's oid in the database.
To open an existing object, you use the open() method. This takes an oid, and
the file permissions. It then returns a LargeObject object.
LargeObject obj = lobj.open(oid,LargeObjectManager.WRITE);
Once the LargeObject is open, you can call methods to read, write, seek etc.
Here's the supported methods:
int oid = obj.getOID(); Return the objects oid
obj.close(); Close the object
byte data[] = obj.read(int len); Read len bytes
onj.read(byte data[],int off,int len); Read into data[off] len bytes
obj.write(byte data[]); Write the array data
obj.write(byte data[],int off,int len); Write len bytes from data[off]
obj.seek(int pos,int ref); As fseek in C.
obj.seek(int pos); Move to pos (from the begining)
int pos = obj.tell(); Returns the current position
int size = obj.size(); Returns the objects size
Caveat: If you commit(), rollback() a transaction, or turn on autocommit whilst
an object is open PostgreSQL will close it. You will need to reopen the object
before using it again. Using the existing LargeObject will cause an
SQLException to be thrown.
------------------
JDBC supports database specific data types using the getObject() call. The
following types have their own Java equivalents supplied by the driver:
box, circle, line, lseg, path, point, polygon
When using the getObject() method on a resultset, it returns a PG_Object,
which holds the postgres type, and its value. This object also supports
methods to retrive these types.
Eg: column 3 contains a point, and rs is the ResultSet:
PG_Object o = (PG_Object)rs.getObject(3);
PGpoint p = o.getPoint();
System.out.println("point returned x="+p.x+", y="+p.y);
Also, when using these classes, their toString() methods return the correct
syntax for writing these to the database.
---------------------------------------------------------------------------

View File

@ -1,363 +0,0 @@
<?xml version="1.0"?>
<!--
Build file to allow ant (http://jakarta.apache.org/ant/) to be used
to build the PostgreSQL JDBC Driver.
This file now requires Ant 1.4.1. 2002-04-18
$PostgreSQL: pgsql/src/interfaces/jdbc/build.xml,v 1.38 2003/11/29 19:52:09 pgsql Exp $
-->
<!DOCTYPE project [
<!ENTITY jarfiles "postgresql.jar,postgresql-examples.jar">
]>
<project name="postgresqlJDBC" default="all" basedir=".">
<!-- set global properties for this build -->
<property name="srcdir" value="." />
<property name="jardir" value="jars" />
<property name="builddir" value="build" />
<property name="package" value="org/postgresql" />
<property name="debug" value="on" />
<property file="build.properties"/>
<!--
This is a simpler method than utils.CheckVersion
It defaults to jdbc1, but builds jdbc2 if the java.lang.Byte class is
in the CLASSPATH (ie JDK1.2 or later), and then enterprise if the
javax.sql.DataSource class is present.
Important: This must have the following order: jdbc1, jdbc2, jdbc3
-->
<target name="check_versions">
<condition property="jdbc1">
<equals arg1="${ant.java.version}" arg2="1.1"/>
</condition>
<condition property="jdbc2">
<or>
<equals arg1="${ant.java.version}" arg2="1.2"/>
<equals arg1="${ant.java.version}" arg2="1.3"/>
</or>
</condition>
<condition property="jdbc3">
<equals arg1="${ant.java.version}" arg2="1.4"/>
</condition>
<available property="datasource" classname="javax.sql.DataSource"/>
<available property="ssl" classname="javax.net.ssl.SSLSocketFactory"/>
<available property="junit" classname="junit.framework.Test"/>
<available property="junit.task" classname="org.apache.tools.ant.taskdefs.optional.junit.JUnitTask"/>
<condition property="jdbc2tests">
<and>
<or>
<isset property="jdbc2"/>
<isset property="jdbc3"/>
</or>
<isset property="junit"/>
</and>
</condition>
<condition property="jdbc2optionaltests">
<and>
<or>
<isset property="jdbc2"/>
<isset property="jdbc3"/>
</or>
<isset property="datasource"/>
<isset property="junit"/>
</and>
</condition>
<condition property="jdbc3tests">
<and>
<isset property="jdbc3"/>
<isset property="junit"/>
</and>
</condition>
</target>
<!-- default target -->
<target name="all">
<antcall target="jar" />
</target>
<!-- create the jar file -->
<target name="jar" depends="compile,examples">
<jar jarfile="${jardir}/postgresql.jar">
<fileset dir="${builddir}">
<include name="${package}/**/*.class" />
</fileset>
<fileset dir="${srcdir}">
<include name="${package}/*.properties" />
</fileset>
</jar>
<jar jarfile="${jardir}/postgresql-examples.jar">
<fileset dir="${builddir}">
<include name="example/**/*.class" />
</fileset>
<fileset dir="${srcdir}">
<include name="example/*.properties" />
</fileset>
</jar>
</target>
<target name="compile" depends="prepare,check_versions,driver">
<available classname="org.postgresql.Driver" property="old.driver.present" />
<fail message="Old driver was detected on classpath or in jre/lib/ext, please remove and try again." if="old.driver.present" />
<javac classpath="{$srcdir}" srcdir="${srcdir}" destdir="${builddir}" debug="${debug}">
<!-- This is the core of the driver. It is common for all three versions. -->
<include name="${package}/*.java" />
<include name="${package}/core/**" />
<include name="${package}/fastpath/**" />
<include name="${package}/geometric/**" />
<include name="${package}/largeobject/**" />
<include name="${package}/util/**" />
<!--
Each jdbcN subpackage is used only if the driver supports *at least* that
revision of JDBC. That is, a JDBC1 build uses only jdbc1, a JDBC2 build
uses both jdbc1 and jdbc2, etc.
Within those subpackages, classes beginning with "JdbcN" are assumed to be
the concrete implementations for JDBC version N and are built only if the
driver supports *exactly* that version. For example, jdbc1/Jdbc1Statement.java
is built only if the driver build is a JDBC1 build.
-->
<!-- jdbc1 subpackage -->
<include name="${package}/jdbc1/**"/>
<exclude name="${package}/jdbc1/Jdbc1*.java" unless="jdbc1"/>
<!-- jdbc2 subpackage -->
<include name="${package}/jdbc2/**" if="jdbc2"/>
<include name="${package}/jdbc2/**" if="jdbc3"/>
<exclude name="${package}/jdbc2/Jdbc2*.java" unless="jdbc2"/>
<exclude name="${package}/jdbc2/optional/**" unless="datasource"/>
<!-- jdbc3 subpackage -->
<include name="${package}/jdbc3/*.java" if="jdbc3"/>
<exclude name="${package}/jdbc3/Jdbc3*.java" unless="jdbc3"/>
</javac>
</target>
<target name="check_driver">
<uptodate targetfile="${package}/Driver.java" property="driver.uptodate">
<srcfiles dir=".">
<include name="${package}/Driver.java.in"/>
<include name="build.properties"/>
</srcfiles>
</uptodate>
</target>
<!--
This generates Driver.java from Driver.java.in
It's required for importing the driver version properties
-->
<target name="driver" depends="prepare,check_versions,check_driver"
unless="driver.uptodate">
<!-- determine the edition text -->
<condition property="edition" value="JDBC1">
<equals arg1="${jdbc1}" arg2="true"/>
</condition>
<condition property="edition" value="JDBC2">
<equals arg1="${jdbc2}" arg2="true"/>
</condition>
<condition property="edition" value="JDBC3">
<equals arg1="${jdbc3}" arg2="true"/>
</condition>
<condition property="edition" value="JDBC2 Enterprise">
<and>
<available classname="javax.sql.DataSource" />
<equals arg1="${jdbc2}" arg2="true"/>
</and>
</condition>
<!-- determine the connection class -->
<condition property="connectclass" value="org.postgresql.jdbc1.Jdbc1Connection">
<equals arg1="${jdbc1}" arg2="true"/>
</condition>
<condition property="connectclass" value="org.postgresql.jdbc2.Jdbc2Connection">
<equals arg1="${jdbc2}" arg2="true"/>
</condition>
<condition property="connectclass" value="org.postgresql.jdbc3.Jdbc3Connection">
<equals arg1="${jdbc3}" arg2="true"/>
</condition>
<!-- determine the ssl status -->
<condition property="ssl_config" value="">
<equals arg1="${ssl}" arg2="true"/>
</condition>
<condition property="ssl_config" value="//">
<not>
<equals arg1="${ssl}" arg2="true"/>
</not>
</condition>
<condition property="ssl_edition" value="SSL">
<equals arg1="${ssl}" arg2="true"/>
</condition>
<condition property="ssl_edition" value="NO SSL">
<not>
<equals arg1="${ssl}" arg2="true"/>
</not>
</condition>
<!-- Some defaults -->
<filter token="MAJORVERSION" value="${major}" />
<filter token="MINORVERSION" value="${minor}" />
<filter token="VERSION" value="PostgreSQL ${fullversion} ${edition} with ${ssl_edition}" />
<filter token="JDBCCONNECTCLASS" value="${connectclass}" />
<filter token="DEF_PGPORT" value="${def_pgport}" />
<filter token="SSL" value="${ssl_config}" />
<fail unless="major" message="'major' undefined. Please follow the directions in README."/>
<fail unless="minor" message="'minor' undefined. Please follow the directions in README."/>
<fail unless="fullversion" message="'fullversion' undefined. Please follow the directions in README."/>
<fail unless="def_pgport" message="'def_pgport' undefined. Please follow the directions in README."/>
<fail unless="enable_debug" message="'enable_debug' undefined. Please follow the directions in README."/>
<!-- Put a check for the current version here -->
<!-- now copy and filter the file -->
<copy file="${package}/Driver.java.in"
overwrite="true"
tofile="${package}/Driver.java"
filtering="yes" />
<echo message="Configured build for the ${edition} edition driver with ${ssl_edition}" />
</target>
<!-- Prepares the build directory -->
<target name="prepare">
<!-- use the enable_debug option from configure -->
<condition property="debug" value="on">
<and>
<equals arg1="${enable_debug}" arg2="yes" />
</and>
</condition>
<mkdir dir="${builddir}" />
<mkdir dir="${jardir}" />
</target>
<!-- This builds the examples -->
<target name="examples" depends="compile">
<javac srcdir="${srcdir}" destdir="${builddir}" debug="${debug}">
<include name="example/**" />
<exclude name="example/corba/**"/>
<exclude name="example/blobtest.java" if="jdbc1"/>
</javac>
</target>
<!-- Builds the corba example -->
<target name="corba" if="jdbc2">
<exec dir="${srcdir}/example/corba" executable="idl2java">
<arg value="stock.idl" />
</exec>
<javac srcdir="${srcdir}" destdir="${builddir}" debug="${debug}">
<include name="example/corba/**" />
</javac>
</target>
<!-- Install the jar files -->
<target name="install" depends="all" if="install.directory">
<copy todir="${install.directory}" overwrite="true">
<fileset dir="${jardir}" includes="&jarfiles;" />
</copy>
</target>
<!-- Uninstall the jar file -->
<target name="uninstall" if="install.directory">
<delete>
<fileset dir="${install.directory}" includes="&jarfiles;" />
</delete>
</target>
<!-- This target removes any class files from the build directory -->
<target name="clean">
<delete quiet="true" dir="${builddir}" />
<delete quiet="true" dir="${jardir}" />
<delete quiet="true" file="${package}/Driver.java" />
</target>
<target name="clean_all" depends="clean">
<delete quiet="true" file="build.properties" />
</target>
<!-- This compiles and executes the JUnit tests -->
<!-- defaults for the tests - override these if required -->
<property name="server" value="localhost" />
<property name="port" value="${def_pgport}" />
<property name="database" value="test" />
<property name="username" value="test" />
<!-- Password must be something. Doesn't matter if trust is used! -->
<property name="password" value="password" />
<!-- The tests now build to a separate directory and jarfile from the
driver build, to ensure we're really testing against the jar we just
built, and not whatever happens to be in builddir. -->
<!-- This compiles and builds the test jarfile. -->
<target name="testjar" depends="jar" if="junit">
<mkdir dir="${builddir}/tests"/>
<javac srcdir="${srcdir}" destdir="${builddir}/tests" debug="${debug}">
<include name="${package}/test/**" />
<exclude name="${package}/test/jdbc2/**" unless="jdbc2tests"/>
<exclude name="${package}/test/jdbc2/optional/**" unless="jdbc2optionaltests" />
<exclude name="${package}/test/jdbc3/**" unless="jdbc3tests" />
<exclude name="${package}/test/util/**" unless="jdbc2optionaltests"/>
<classpath>
<pathelement location="${jardir}/postgresql.jar"/>
</classpath>
</javac>
<jar jarfile="${jardir}/postgresql-tests.jar" basedir="${builddir}/tests"/>
</target>
<!-- This actually runs the tests -->
<target name="runtest" depends="testjar" if="junit.task">
<junit>
<formatter type="brief" usefile="false"/>
<sysproperty key="server" value="${server}" />
<sysproperty key="port" value="${port}" />
<sysproperty key="database" value="${database}" />
<sysproperty key="username" value="${username}" />
<sysproperty key="password" value="${password}" />
<classpath>
<pathelement location="${jardir}/postgresql.jar" />
<pathelement location="${jardir}/postgresql-tests.jar" />
<pathelement path="${java.class.path}" />
</classpath>
<test name="org.postgresql.test.jdbc2.Jdbc2TestSuite" if="jdbc2tests"/>
<test name="org.postgresql.test.jdbc2.optional.OptionalTestSuite" if="jdbc2optionaltests"/>
<test name="org.postgresql.test.jdbc3.Jdbc3TestSuite" if="jdbc3tests"/>
</junit>
</target>
<!-- This is the target invoked by the Makefile -->
<target name="test" depends="testjar,runtest"/>
</project>

View File

@ -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();
}
}
}

View File

@ -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();
}
}

View File

@ -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();
}
}
}

View File

@ -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();
}
}
}

View File

@ -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;
}
}

View File

@ -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");
}
}

View File

@ -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;
}
}
}

View File

@ -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;
}
}

View File

@ -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();
}
}
}

View File

@ -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

View File

@ -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);
};
};

View File

@ -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;

View File

@ -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();
}
}
}

View File

@ -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();
}
}
}

View File

@ -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();
}
}
}

View File

@ -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();
}
}
}

View File

@ -1,503 +0,0 @@
/*-------------------------------------------------------------------------
*
* Driver.java(.in)
* The Postgresql JDBC Driver implementation
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/Driver.java.in,v 1.40 2003/12/11 18:10:40 davec Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql;
import java.io.*;
import java.sql.*;
import java.util.*;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
/*
* The Java SQL framework allows for multiple database drivers. Each
* driver should supply a class that implements the Driver interface
*
* <p>The DriverManager will try to load as many drivers as it can find and
* then for any given connection request, it will ask each driver in turn
* to try to connect to the target URL.
*
* <p>It is strongly recommended that each Driver class should be small and
* standalone so that the Driver class can be loaded and queried without
* bringing in vast quantities of supporting code.
*
* <p>When a Driver class is loaded, it should create an instance of itself
* and register it with the DriverManager. This means that a user can load
* and register a driver by doing Class.forName("foo.bah.Driver")
*
* @see org.postgresql.PGConnection
* @see java.sql.Driver
*/
public class Driver implements java.sql.Driver
{
// make these public so they can be used in setLogLevel below
public static final int DEBUG = 2;
public static final int INFO = 1;
public static boolean logDebug = false;
public static boolean logInfo = false;
static
{
try
{
// moved the registerDriver from the constructor to here
// because some clients call the driver themselves (I know, as
// my early jdbc work did - and that was based on other examples).
// Placing it here, means that the driver is registered once only.
java.sql.DriverManager.registerDriver(new Driver());
}
catch (SQLException e)
{
e.printStackTrace();
}
}
/*
* Try to make a database connection to the given URL. The driver
* should return "null" if it realizes it is the wrong kind of
* driver to connect to the given URL. This will be common, as
* when the JDBC driverManager is asked to connect to a given URL,
* it passes the URL to each loaded driver in turn.
*
* <p>The driver should raise an SQLException if it is the right driver
* to connect to the given URL, but has trouble connecting to the
* database.
*
* <p>The java.util.Properties argument can be used to pass arbitrary
* string tag/value pairs as connection arguments.
*
* user - (optional) The user to connect as
* password - (optional) The password for the user
* ssl - (optional) Use SSL when connecting to the server
* charSet - (optional) The character set to be used for converting
* to/from the database to unicode. If multibyte is enabled on the
* server then the character set of the database is used as the default,
* otherwise the jvm character encoding is used as the default.
* This value is only used when connecting to a 7.2 or older server.
* loglevel - (optional) Enable logging of messages from the driver.
* The value is an integer from 1 to 2 where:
* INFO = 1, DEBUG = 2
* The output is sent to DriverManager.getPrintWriter() if set,
* otherwise it is sent to System.out.
* compatible - (optional) This is used to toggle
* between different functionality as it changes across different releases
* of the jdbc driver code. The values here are versions of the jdbc
* client and not server versions. For example in 7.1 get/setBytes
* worked on LargeObject values, in 7.2 these methods were changed
* to work on bytea values. This change in functionality could
* be disabled by setting the compatible level to be "7.1", in
* which case the driver will revert to the 7.1 functionality.
*
* <p>Normally, at least
* "user" and "password" properties should be included in the
* properties. For a list of supported
* character encoding , see
* http://java.sun.com/products/jdk/1.2/docs/guide/internat/encoding.doc.html
* Note that you will probably want to have set up the Postgres database
* itself to use the same encoding, with the "-E <encoding>" argument
* to createdb.
*
* Our protocol takes the forms:
* <PRE>
* jdbc:postgresql://host:port/database?param1=val1&...
* </PRE>
*
* @param url the URL of the database to connect to
* @param info a list of arbitrary tag/value pairs as connection
* arguments
* @return a connection to the URL or null if it isnt us
* @exception SQLException if a database access error occurs
* @see java.sql.Driver#connect
*/
public java.sql.Connection connect(String url, Properties info) throws SQLException
{
Properties props;
if ((props = parseURL(url, info)) == null)
{
if (Driver.logDebug)
Driver.debug("Error in url" + url);
return null;
}
try
{
if (Driver.logDebug)
Driver.debug("connect " + url);
@JDBCCONNECTCLASS@ con = (@JDBCCONNECTCLASS@)(Class.forName("@JDBCCONNECTCLASS@").newInstance());
con.openConnection (host(props), port(props), props, database(props), url, this);
return (java.sql.Connection)con;
}
catch (ClassNotFoundException ex)
{
if (Driver.logDebug)
Driver.debug("error", ex);
throw new PSQLException("postgresql.jvm.version", PSQLState.SYSTEM_ERROR, ex);
}
catch (PSQLException ex1)
{
// re-throw the exception, otherwise it will be caught next, and a
// org.postgresql.unusual error will be returned instead.
throw ex1;
}
catch (Exception ex2)
{
if (Driver.logDebug) {
Driver.debug("error", ex2);
}
throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, ex2);
}
}
/*
* Returns true if the driver thinks it can open a connection to the
* given URL. Typically, drivers will return true if they understand
* the subprotocol specified in the URL and false if they don't. Our
* protocols start with jdbc:postgresql:
*
* @see java.sql.Driver#acceptsURL
* @param url the URL of the driver
* @return true if this driver accepts the given URL
* @exception SQLException if a database-access error occurs
* (Dont know why it would *shrug*)
*/
public boolean acceptsURL(String url) throws SQLException
{
if (parseURL(url, null) == null)
return false;
return true;
}
/*
* The getPropertyInfo method is intended to allow a generic GUI
* tool to discover what properties it should prompt a human for
* in order to get enough information to connect to a database.
*
* <p>Note that depending on the values the human has supplied so
* far, additional values may become necessary, so it may be necessary
* to iterate through several calls to getPropertyInfo
*
* @param url the Url of the database to connect to
* @param info a proposed list of tag/value pairs that will be sent on
* connect open.
* @return An array of DriverPropertyInfo objects describing
* possible properties. This array may be an empty array if
* no properties are required
* @exception SQLException if a database-access error occurs
* @see java.sql.Driver#getPropertyInfo
*/
public DriverPropertyInfo[] getPropertyInfo(String url, Properties info) throws SQLException
{
//This method isn't really implemented
//we just parse the URL to ensure it is valid
parseURL(url, info);
return new DriverPropertyInfo[0];
}
/*
* Gets the drivers major version number
*
* @return the drivers major version number
*/
public int getMajorVersion()
{
return @MAJORVERSION@;
}
/*
* Get the drivers minor version number
*
* @return the drivers minor version number
*/
public int getMinorVersion()
{
return @MINORVERSION@;
}
/*
* Returns the VERSION variable from Makefile.global
*/
public static String getVersion()
{
return "@VERSION@ (build " + m_buildNumber + ")";
}
/*
* Report whether the driver is a genuine JDBC compliant driver. A
* driver may only report "true" here if it passes the JDBC compliance
* tests, otherwise it is required to return false. JDBC compliance
* requires full support for the JDBC API and full support for SQL 92
* Entry Level.
*
* <p>For PostgreSQL, this is not yet possible, as we are not SQL92
* compliant (yet).
*/
public boolean jdbcCompliant()
{
return false;
}
static private String[] protocols = { "jdbc", "postgresql" };
/*
* Constructs a new DriverURL, splitting the specified URL into its
* component parts
* @param url JDBC URL to parse
* @param defaults Default properties
* @return Properties with elements added from the url
* @exception SQLException
*/
Properties parseURL(String url, Properties defaults) throws SQLException
{
int state = -1;
Properties urlProps = new Properties(defaults);
String l_urlServer = url;
String l_urlArgs = "";
int l_qPos = url.indexOf('?');
if (l_qPos != -1) {
l_urlServer = url.substring(0,l_qPos);
l_urlArgs = url.substring(l_qPos+1);
}
// look for an IPv6 address that is enclosed by []
// the upcoming parsing that uses colons as identifiers can't handle
// the colons in an IPv6 address.
int ipv6start = l_urlServer.indexOf("[");
int ipv6end = l_urlServer.indexOf("]");
String ipv6address = null;
if (ipv6start != -1 && ipv6end > ipv6start) {
ipv6address = l_urlServer.substring(ipv6start+1,ipv6end);
l_urlServer = l_urlServer.substring(0,ipv6start)+"ipv6host"+l_urlServer.substring(ipv6end+1);
}
//parse the server part of the url
StringTokenizer st = new StringTokenizer(l_urlServer, ":/", true);
int count;
for (count = 0; (st.hasMoreTokens()); count++)
{
String token = st.nextToken();
// PM Aug 2 1997 - Modified to allow multiple backends
if (count <= 3)
{
if ((count % 2) == 1 && token.equals(":"))
;
else if ((count % 2) == 0)
{
boolean found = (count == 0) ? true : false;
for (int tmp = 0;tmp < protocols.length;tmp++)
{
if (token.equals(protocols[tmp]))
{
// PM June 29 1997 Added this property to enable the driver
// to handle multiple backend protocols.
if (count == 2 && tmp > 0)
{
urlProps.put("Protocol", token);
found = true;
}
}
}
if (found == false)
return null;
}
else
return null;
}
else if (count > 3)
{
if (count == 4 && token.equals("/"))
state = 0;
else if (count == 4)
{
urlProps.put("PGDBNAME", token);
state = -2;
}
else if (count == 5 && state == 0 && token.equals("/"))
state = 1;
else if (count == 5 && state == 0)
return null;
else if (count == 6 && state == 1)
urlProps.put("PGHOST", token);
else if (count == 7 && token.equals(":"))
state = 2;
else if (count == 8 && state == 2)
{
try
{
Integer portNumber = Integer.decode(token);
urlProps.put("PGPORT", portNumber.toString());
}
catch (Exception e)
{
return null;
}
}
else if ((count == 7 || count == 9) &&
(state == 1 || state == 2) && token.equals("/"))
state = -1;
else if (state == -1)
{
urlProps.put("PGDBNAME", token);
state = -2;
}
}
}
if (count <= 1) {
return null;
}
// if we extracted an IPv6 address out earlier put it back
if (ipv6address != null)
urlProps.put("PGHOST",ipv6address);
//parse the args part of the url
StringTokenizer qst = new StringTokenizer(l_urlArgs, "&");
for (count = 0; (qst.hasMoreTokens()); count++)
{
String token = qst.nextToken();
int l_pos = token.indexOf('=');
if (l_pos == -1) {
urlProps.put(token, "");
} else {
urlProps.put(token.substring(0,l_pos), token.substring(l_pos+1));
}
}
return urlProps;
}
/*
* @return the hostname portion of the URL
*/
public String host(Properties props)
{
return props.getProperty("PGHOST", "localhost");
}
/*
* @return the port number portion of the URL or the default if no port was specified
*/
public int port(Properties props)
{
return Integer.parseInt(props.getProperty("PGPORT", "@DEF_PGPORT@"));
}
/*
* @return the database name of the URL
*/
public String database(Properties props)
{
return props.getProperty("PGDBNAME", "");
}
/*
* This method was added in v6.5, and simply throws an SQLException
* for an unimplemented method. I decided to do it this way while
* implementing the JDBC2 extensions to JDBC, as it should help keep the
* overall driver size down.
*/
public static SQLException notImplemented()
{
return new PSQLException("postgresql.unimplemented", PSQLState.NOT_IMPLEMENTED);
}
/**
* used to turn logging on to a certain level, can be called
* by specifying fully qualified class ie org.postgresql.Driver.setLogLevel()
* @param logLevel sets the level which logging will respond to
* INFO being almost no messages
* DEBUG most verbose
*/
public static void setLogLevel(int logLevel)
{
logDebug = (logLevel >= DEBUG) ? true : false;
logInfo = (logLevel >= INFO) ? true : false;
}
/*
* logging message at the debug level
* messages will be printed if the logging level is less or equal to DEBUG
*/
public static void debug(String msg)
{
if (logDebug)
{
DriverManager.println(msg);
}
}
/*
* logging message at the debug level
* messages will be printed if the logging level is less or equal to DEBUG
*/
public static void debug(String msg, Exception ex)
{
if (logDebug)
{
DriverManager.println(msg);
if(ex != null) {
DriverManager.println(ex.toString());
}
}
}
/*
* logging message at info level
* messages will be printed if the logging level is less or equal to INFO
*/
public static void info(String msg)
{
if (logInfo)
{
DriverManager.println(msg);
}
}
/*
* logging message at info level
* messages will be printed if the logging level is less or equal to INFO
*/
public static void info(String msg, Exception ex)
{
if (logInfo)
{
DriverManager.println(msg);
if(ex != null) {
DriverManager.println(ex.toString());
}
}
}
public static void makeSSL(org.postgresql.core.PGStream p_stream) throws IOException {
@SSL@ if (logDebug)
@SSL@ debug("converting regular socket connection to ssl");
@SSL@ javax.net.ssl.SSLSocketFactory factory = (javax.net.ssl.SSLSocketFactory) javax.net.ssl.SSLSocketFactory.getDefault();
@SSL@ p_stream.connection = (javax.net.ssl.SSLSocket) factory.createSocket(p_stream.connection,p_stream.host,p_stream.port,true);
@SSL@ p_stream.pg_input = new BufferedInputStream(p_stream.connection.getInputStream(), 8192);
@SSL@ p_stream.pg_output = new BufferedOutputStream(p_stream.connection.getOutputStream(), 8192);
}
public static boolean sslEnabled() {
boolean l_return = false;
@SSL@ l_return = true;
return l_return;
}
//The build number should be incremented for every new build
private static int m_buildNumber = 300;
}

View File

@ -1,87 +0,0 @@
/*-------------------------------------------------------------------------
*
* PGConnection.java
* The public interface definition for a Postgresql Connection
* This interface defines PostgreSQL extentions to the java.sql.Connection
* interface. Any java.sql.Connection object returned by the driver will
* also implement this interface
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/PGConnection.java,v 1.7 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql;
import java.sql.*;
import org.postgresql.core.Encoding;
import org.postgresql.fastpath.Fastpath;
import org.postgresql.largeobject.LargeObjectManager;
public interface PGConnection
{
/**
* This method returns any notifications that have been received
* since the last call to this method.
* Returns null if there have been no notifications.
* @since 7.3
*/
public PGNotification[] getNotifications();
/**
* This returns the LargeObject API for the current connection.
* @since 7.3
*/
public LargeObjectManager getLargeObjectAPI() throws SQLException;
/**
* This returns the Fastpath API for the current connection.
* @since 7.3
*/
public Fastpath getFastpathAPI() throws SQLException;
/*
* This allows client code to add a handler for one of org.postgresql's
* more unique data types.
*
* <p><b>NOTE:</b> This is not part of JDBC, but an extension.
*
* <p>The best way to use this is as follows:
*
* <p><pre>
* ...
* ((org.postgresql.PGConnection)myconn).addDataType("mytype","my.class.name");
* ...
* </pre>
*
* <p>where myconn is an open Connection to org.postgresql.
*
* <p>The handling class must extend org.postgresql.util.PGobject
*
* @see org.postgresql.util.PGobject
*/
public void addDataType(String type, String name);
/** @deprecated */
public Encoding getEncoding() throws SQLException;
/** @deprecated */
public int getSQLType(String pgTypeName) throws SQLException;
/** @deprecated */
public int getSQLType(int oid) throws SQLException;
/** @deprecated */
public String getPGType(int oid) throws SQLException;
/** @deprecated */
public int getPGType(String typeName) throws SQLException;
/** @deprecated */
public Object getObject(String type, String value) throws SQLException;
}

View File

@ -1,31 +0,0 @@
/*-------------------------------------------------------------------------
*
* PGNotification.java
* This interface defines public PostgreSQL extention for Notifications
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/PGNotification.java,v 1.4 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql;
public interface PGNotification
{
/**
* Returns name of this notification
* @since 7.3
*/
public String getName();
/**
* Returns the process id of the backend process making this notification
* @since 7.3
*/
public int getPID();
}

View File

@ -1,25 +0,0 @@
/*-------------------------------------------------------------------------
*
* PGRefCursorResultSet.java
* Describes a PLPGSQL refcursor type.
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/PGRefCursorResultSet.java,v 1.2 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql;
/** A ref cursor based result set.
*/
public interface PGRefCursorResultSet
{
/** return the name of the cursor.
*/
public String getRefCursor ();
}

View File

@ -1,43 +0,0 @@
/*-------------------------------------------------------------------------
*
* PGStatement.java
* This interface defines PostgreSQL extentions to the java.sql.Statement
* interface. Any java.sql.Statement object returned by the driver will
* also implement this interface
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/PGStatement.java,v 1.8 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql;
import java.sql.*;
public interface PGStatement
{
/**
* Returns the Last inserted/updated oid.
* @return OID of last insert
* @since 7.3
*/
public long getLastOID() throws SQLException;
/**
* Turn on the use of prepared statements in the server (server side
* prepared statements are unrelated to jdbc PreparedStatements)
* @since 7.3
*/
public void setUseServerPrepare(boolean flag) throws SQLException;
/**
* Is this statement using server side prepared statements
* @since 7.3
*/
public boolean isUseServerPrepare();
}

View File

@ -1,47 +0,0 @@
/*-------------------------------------------------------------------------
*
* BaseConnection.java
* The internal interface definition for a jdbc connection
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/core/BaseConnection.java,v 1.5 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.core;
import java.sql.DatabaseMetaData;
import java.sql.Statement;
import java.sql.SQLException;
import org.postgresql.PGConnection;
import org.postgresql.PGNotification;
public interface BaseConnection extends PGConnection
{
public void addNotification(PGNotification p_notification);
public void addWarning(String msg);
public void cancelQuery() throws SQLException;
public Statement createStatement() throws SQLException;
public BaseResultSet execSQL(String s) throws SQLException;
public boolean getAutoCommit();
public String getCursorName() throws SQLException;
public Encoding getEncoding() throws SQLException;
public DatabaseMetaData getMetaData() throws SQLException;
public Object getObject(String type, String value) throws SQLException;
public int getPGProtocolVersionMajor();
public int getPGProtocolVersionMinor();
public PGStream getPGStream();
public String getPGType(int oid) throws SQLException;
public int getPGType(String pgTypeName) throws SQLException;
public int getSQLType(int oid) throws SQLException;
public int getSQLType(String pgTypeName) throws SQLException;
public boolean haveMinimumCompatibleVersion(String ver) throws SQLException;
public boolean haveMinimumServerVersion(String ver) throws SQLException;
public void setAutoCommit(boolean autoCommit) throws SQLException;
public void setCursorName(String cursor) throws SQLException;
}

View File

@ -1,50 +0,0 @@
/*-------------------------------------------------------------------------
*
* BaseResultSet.java
* The internal interface definition for a jdbc result set
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/core/BaseResultSet.java,v 1.3 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.core;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Vector;
public interface BaseResultSet
{
public BaseStatement getPGStatement();
public void append(BaseResultSet r);
public void close() throws SQLException;
public int getColumnCount();
public String getCursorName() throws SQLException;
public SimpleDateFormat getDateFormat();
public String getFixedString(int col) throws SQLException;
public long getLastOID();
public ResultSetMetaData getMetaData() throws SQLException;
public ResultSet getNext();
public Object getObject(int columnIndex) throws SQLException;
public int getResultCount();
public String getStatusString();
public String getString(int columnIndex) throws SQLException;
public StringBuffer getStringBuffer();
public SimpleDateFormat getTimestampFormat();
public SimpleDateFormat getTimestampTZFormat();
public int getTupleCount();
public boolean next() throws SQLException;
public boolean reallyResultSet();
public void reInit (Field[] fields, Vector tuples, String status,
int updateCount, long insertOID, boolean binaryCursor);
public void setStatement(BaseStatement statement);
}

View File

@ -1,41 +0,0 @@
/*-------------------------------------------------------------------------
*
* BaseStatement.java
* The internal interface definition for a jdbc statement
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/core/BaseStatement.java,v 1.7 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.core;
import org.postgresql.PGRefCursorResultSet;
import java.sql.*;
import java.util.Vector;
public interface BaseStatement extends org.postgresql.PGStatement
{
public BaseResultSet createResultSet(Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException;
public PGRefCursorResultSet createRefCursorResultSet(String cursorName) throws SQLException;
public BaseConnection getPGConnection();
/*
* The maxRows limit is set to limit the number of rows that
* any ResultSet can contain. If the limit is exceeded, the
* excess rows are silently dropped.
*/
public void addWarning(String p_warning) throws SQLException;
public void close() throws SQLException;
public int getFetchSize();
public int getMaxFieldSize() throws SQLException;
public int getMaxRows() throws SQLException;
public int getResultSetConcurrency() throws SQLException;
public String getFetchingCursorName();
public SQLWarning getWarnings() throws SQLException;
public void setMaxFieldSize(int max) throws SQLException;
}

View File

@ -1,291 +0,0 @@
/*-------------------------------------------------------------------------
*
* Encoding.java
* Converts to and from the character encoding used by the backend.
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/core/Encoding.java,v 1.13 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.core;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.Hashtable;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
public class Encoding
{
private static final Encoding DEFAULT_ENCODING = new Encoding(null);
/*
* Preferred JVM encodings for backend encodings.
*/
private static final Hashtable encodings = new Hashtable();
static {
//Note: this list should match the set of supported server
// encodings found in backend/util/mb/encnames.c
encodings.put("SQL_ASCII", new String[] { "ASCII", "us-ascii" });
encodings.put("UNICODE", new String[] { "UTF-8", "UTF8" });
encodings.put("LATIN1", new String[] { "ISO8859_1" });
encodings.put("LATIN2", new String[] { "ISO8859_2" });
encodings.put("LATIN3", new String[] { "ISO8859_3" });
encodings.put("LATIN4", new String[] { "ISO8859_4" });
encodings.put("ISO_8859_5", new String[] { "ISO8859_5" });
encodings.put("ISO_8859_6", new String[] { "ISO8859_6" });
encodings.put("ISO_8859_7", new String[] { "ISO8859_7" });
encodings.put("ISO_8859_8", new String[] { "ISO8859_8" });
encodings.put("LATIN5", new String[] { "ISO8859_9" });
encodings.put("LATIN7", new String[] { "ISO8859_13" });
encodings.put("LATIN9", new String[] { "ISO8859_15_FDIS" });
encodings.put("EUC_JP", new String[] { "EUC_JP" });
encodings.put("EUC_CN", new String[] { "EUC_CN" });
encodings.put("EUC_KR", new String[] { "EUC_KR" });
encodings.put("JOHAB", new String[] { "Johab" });
encodings.put("EUC_TW", new String[] { "EUC_TW" });
encodings.put("SJIS", new String[] { "MS932", "SJIS" });
encodings.put("BIG5", new String[] { "Big5", "MS950", "Cp950" });
encodings.put("GBK", new String[] { "GBK", "MS936" });
encodings.put("UHC", new String[] { "MS949", "Cp949", "Cp949C" });
encodings.put("TCVN", new String[] { "Cp1258" });
encodings.put("WIN1256", new String[] { "Cp1256" });
encodings.put("WIN1250", new String[] { "Cp1250" });
encodings.put("WIN874", new String[] { "MS874", "Cp874" });
encodings.put("WIN", new String[] { "Cp1251" });
encodings.put("ALT", new String[] { "Cp866" });
// We prefer KOI8-U, since it is a superset of KOI8-R.
encodings.put("KOI8", new String[] { "KOI8_U", "KOI8_R" });
// If the database isn't encoding-aware then we can't have
// any preferred encodings.
encodings.put("UNKNOWN", new String[0]);
// The following encodings do not have a java equivalent
encodings.put("MULE_INTERNAL", new String[0]);
encodings.put("LATIN6", new String[0]);
encodings.put("LATIN8", new String[0]);
encodings.put("LATIN10", new String[0]);
}
private final String encoding;
private Encoding(String encoding)
{
this.encoding = encoding;
}
/*
* Get an Encoding for from the given database encoding and
* the encoding passed in by the user.
*/
public static Encoding getEncoding(String databaseEncoding,
String passedEncoding)
{
if (passedEncoding != null)
{
if (isAvailable(passedEncoding))
{
return new Encoding(passedEncoding);
}
else
{
return defaultEncoding();
}
}
else
{
return encodingForDatabaseEncoding(databaseEncoding);
}
}
/*
* Get an Encoding matching the given database encoding.
*/
private static Encoding encodingForDatabaseEncoding(String databaseEncoding)
{
// If the backend encoding is known and there is a suitable
// encoding in the JVM we use that. Otherwise we fall back
// to the default encoding of the JVM.
if (encodings.containsKey(databaseEncoding))
{
String[] candidates = (String[]) encodings.get(databaseEncoding);
for (int i = 0; i < candidates.length; i++)
{
if (isAvailable(candidates[i]))
{
return new Encoding(candidates[i]);
}
}
}
return defaultEncoding();
}
/*
* Name of the (JVM) encoding used.
*/
public String name()
{
return encoding;
}
/*
* Encode a string to an array of bytes.
*/
public byte[] encode(String s) throws SQLException
{
byte[] l_return;
try
{
if (encoding == null)
{
l_return = s.getBytes();
}
else
{
l_return = s.getBytes(encoding);
}
//Don't return null, return an empty byte[] instead
if (l_return == null) {
return new byte[0];
} else {
return l_return;
}
}
catch (UnsupportedEncodingException e)
{
throw new PSQLException("postgresql.stream.encoding", PSQLState.DATA_ERROR, e);
}
}
/*
* Decode an array of bytes into a string.
*/
public String decode(byte[] encodedString, int offset, int length) throws SQLException
{
try
{
if (encoding == null)
{
return new String(encodedString, offset, length);
}
else
{
if (encoding.equals("UTF-8")) {
return decodeUTF8(encodedString, offset, length);
}
return new String(encodedString, offset, length, encoding);
}
}
catch (UnsupportedEncodingException e)
{
throw new PSQLException("postgresql.stream.encoding", PSQLState.DATA_ERROR, e);
}
}
/*
* Decode an array of bytes into a string.
*/
public String decode(byte[] encodedString) throws SQLException
{
return decode(encodedString, 0, encodedString.length);
}
/*
* Get a Reader that decodes the given InputStream.
*/
public Reader getDecodingReader(InputStream in) throws SQLException
{
try
{
if (encoding == null)
{
return new InputStreamReader(in);
}
else
{
return new InputStreamReader(in, encoding);
}
}
catch (UnsupportedEncodingException e)
{
throw new PSQLException("postgresql.res.encoding", PSQLState.DATA_ERROR, e);
}
}
/*
* Get an Encoding using the default encoding for the JVM.
*/
public static Encoding defaultEncoding()
{
return DEFAULT_ENCODING;
}
/*
* Test if an encoding is available in the JVM.
*/
private static boolean isAvailable(String encodingName)
{
try
{
"DUMMY".getBytes(encodingName);
return true;
}
catch (UnsupportedEncodingException e)
{
return false;
}
}
/**
* custom byte[] -> String conversion routine, 3x-10x faster than
* standard new String(byte[])
*/
private static final int pow2_6 = 64; // 26
private static final int pow2_12 = 4096; // 212
private char[] cdata = new char[50];
private synchronized String decodeUTF8(byte data[], int offset, int length) throws SQLException {
try {
char[] l_cdata = cdata;
if (l_cdata.length < (length)) {
l_cdata = new char[length];
}
int i = offset;
int j = 0;
int k = length + offset;
int z, y, x, val;
while (i < k) {
z = data[i] & 0xFF;
if (z < 0x80) {
l_cdata[j++] = (char)data[i];
i++;
} else if (z >= 0xE0) { // length == 3
y = data[i+1] & 0xFF;
x = data[i+2] & 0xFF;
val = (z-0xE0)*pow2_12 + (y-0x80)*pow2_6 + (x-0x80);
l_cdata[j++] = (char) val;
i+= 3;
} else { // length == 2 (maybe add checking for length > 3, throw exception if it is
y = data[i+1] & 0xFF;
val = (z - 0xC0)* (pow2_6)+(y-0x80);
l_cdata[j++] = (char) val;
i+=2;
}
}
String s = new String(l_cdata, 0, j);
return s;
} catch (Exception l_e) {
throw new PSQLException("postgresql.con.invalidchar", l_e);
}
}
}

View File

@ -1,114 +0,0 @@
/*-------------------------------------------------------------------------
*
* Field.java
* Field is a class used to describe fields in a PostgreSQL ResultSet
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/core/Field.java,v 1.3 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.core;
import java.sql.*;
import org.postgresql.core.BaseConnection;
/*
*/
public class Field
{
private int length; // Internal Length of this field
private int oid; // OID of the type
private int mod; // type modifier of this field
private String name; // Name of this field
private BaseConnection conn; // Connection Instantation
/*
* Construct a field based on the information fed to it.
*
* @param conn the connection this field came from
* @param name the name of the field
* @param oid the OID of the field
* @param len the length of the field
*/
public Field(BaseConnection conn, String name, int oid, int length, int mod)
{
this.conn = conn;
this.name = name;
this.oid = oid;
this.length = length;
this.mod = mod;
}
/*
* Constructor without mod parameter.
*
* @param conn the connection this field came from
* @param name the name of the field
* @param oid the OID of the field
* @param len the length of the field
*/
public Field(BaseConnection conn, String name, int oid, int length)
{
this(conn, name, oid, length, 0);
}
/*
* @return the oid of this Field's data type
*/
public int getOID()
{
return oid;
}
/*
* @return the mod of this Field's data type
*/
public int getMod()
{
return mod;
}
/*
* @return the name of this Field's data type
*/
public String getName()
{
return name;
}
/*
* @return the length of this Field's data type
*/
public int getLength()
{
return length;
}
/*
* We also need to get the PG type name as returned by the back end.
*
* @return the String representation of the PG type of this field
* @exception SQLException if a database access error occurs
*/
public String getPGType() throws SQLException
{
return conn.getPGType(oid);
}
/*
* We also need to get the java.sql.types type.
*
* @return the int representation of the java.sql.types type of this field
* @exception SQLException if a database access error occurs
*/
public int getSQLType() throws SQLException
{
return conn.getSQLType(oid);
}
}

View File

@ -1,45 +0,0 @@
/*-------------------------------------------------------------------------
*
* Notification.java
* This is the implementation of the PGNotification interface
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/core/Notification.java,v 1.4 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.core;
import org.postgresql.PGNotification;
public class Notification implements PGNotification
{
public Notification(String p_name, int p_pid)
{
m_name = p_name;
m_pid = p_pid;
}
/*
* Returns name of this notification
*/
public String getName()
{
return m_name;
}
/*
* Returns the process id of the backend process making this notification
*/
public int getPID()
{
return m_pid;
}
private String m_name;
private int m_pid;
}

View File

@ -1,431 +0,0 @@
/*-------------------------------------------------------------------------
*
* PGStream.java
* This class is used by Connection for communicating with the
* backend.
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/core/PGStream.java,v 1.4 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.core;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.InputStream;
import java.io.IOException;
import java.net.Socket;
import java.sql.*;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
public class PGStream
{
public String host;
public int port;
public Socket connection;
public InputStream pg_input;
public BufferedOutputStream pg_output;
private byte[] byte_buf = new byte[8*1024];
/*
* Constructor: Connect to the PostgreSQL back end and return
* a stream connection.
*
* @param host the hostname to connect to
* @param port the port number that the postmaster is sitting on
* @exception IOException if an IOException occurs below it.
*/
public PGStream(String p_host, int p_port) throws IOException
{
host = p_host;
port = p_port;
connection = new Socket(host, port);
// Submitted by Jason Venner <jason@idiom.com> adds a 10x speed
// improvement on FreeBSD machines (caused by a bug in their TCP Stack)
connection.setTcpNoDelay(true);
// Buffer sizes submitted by Sverre H Huseby <sverrehu@online.no>
pg_input = new BufferedInputStream(connection.getInputStream(), 8192);
pg_output = new BufferedOutputStream(connection.getOutputStream(), 8192);
}
/*
* Sends a single character to the back end
*
* @param val the character to be sent
* @exception IOException if an I/O error occurs
*/
public void SendChar(int val) throws IOException
{
pg_output.write((byte)val);
}
/*
* Sends an integer to the back end
*
* @param val the integer to be sent
* @param siz the length of the integer in bytes (size of structure)
* @exception IOException if an I/O error occurs
*/
public void SendInteger(int val, int siz) throws IOException
{
byte[] buf = new byte[siz];
while (siz-- > 0)
{
buf[siz] = (byte)(val & 0xff);
val >>= 8;
}
Send(buf);
}
/*
* Sends an integer to the back end
*
* @param val the integer to be sent
* @param siz the length of the integer in bytes (size of structure)
* @exception IOException if an I/O error occurs
*/
public void SendIntegerR(int val, int siz) throws IOException
{
byte[] buf = new byte[siz];
for (int i = 0; i < siz; i++)
{
buf[i] = (byte)(val & 0xff);
val >>= 8;
}
Send(buf);
}
/*
* Send an array of bytes to the backend
*
* @param buf The array of bytes to be sent
* @exception IOException if an I/O error occurs
*/
public void Send(byte buf[]) throws IOException
{
pg_output.write(buf);
}
/*
* Send an exact array of bytes to the backend - if the length
* has not been reached, send nulls until it has.
*
* @param buf the array of bytes to be sent
* @param siz the number of bytes to be sent
* @exception IOException if an I/O error occurs
*/
public void Send(byte buf[], int siz) throws IOException
{
Send(buf, 0, siz);
}
/*
* Send an exact array of bytes to the backend - if the length
* has not been reached, send nulls until it has.
*
* @param buf the array of bytes to be sent
* @param off offset in the array to start sending from
* @param siz the number of bytes to be sent
* @exception IOException if an I/O error occurs
*/
public void Send(byte buf[], int off, int siz) throws IOException
{
int i;
pg_output.write(buf, off, ((buf.length - off) < siz ? (buf.length - off) : siz));
if ((buf.length - off) < siz)
{
for (i = buf.length - off ; i < siz ; ++i)
{
pg_output.write(0);
}
}
}
/*
* Receives a single character from the backend
*
* @return the character received
* @exception SQLException if an I/O Error returns
*/
public int ReceiveChar() throws SQLException
{
int c = 0;
try
{
c = pg_input.read();
if (c < 0)
throw new PSQLException("postgresql.stream.eof", PSQLState.COMMUNICATION_ERROR);
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", PSQLState.COMMUNICATION_ERROR, e);
}
return c;
}
/*
* Receives an integer from the backend
*
* @param siz length of the integer in bytes
* @return the integer received from the backend
* @exception SQLException if an I/O error occurs
*/
public int ReceiveInteger(int siz) throws SQLException
{
int n = 0;
try
{
for (int i = 0 ; i < siz ; i++)
{
int b = pg_input.read();
if (b < 0)
throw new PSQLException("postgresql.stream.eof", PSQLState.COMMUNICATION_ERROR);
n = n | (b << (8 * i)) ;
}
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", PSQLState.COMMUNICATION_ERROR, e);
}
return n;
}
/*
* Receives an integer from the backend
*
* @param siz length of the integer in bytes
* @return the integer received from the backend
* @exception SQLException if an I/O error occurs
*/
public int ReceiveIntegerR(int siz) throws SQLException
{
int n = 0;
try
{
for (int i = 0 ; i < siz ; i++)
{
int b = pg_input.read();
if (b < 0)
throw new PSQLException("postgresql.stream.eof", PSQLState.COMMUNICATION_ERROR);
n = b | (n << 8);
}
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", PSQLState.COMMUNICATION_ERROR, e);
}
return n;
}
/*
* Receives a null-terminated string from the backend. If we don't see a
* null, then we assume something has gone wrong.
*
* @param encoding the charset encoding to use.
* @return string from back end
* @exception SQLException if an I/O error occurs, or end of file
*/
public String ReceiveString(Encoding encoding)
throws SQLException
{
int s = 0;
byte[] rst = byte_buf;
try
{
int buflen = rst.length;
boolean done = false;
while (!done)
{
while (s < buflen)
{
int c = pg_input.read();
if (c < 0)
throw new PSQLException("postgresql.stream.eof", PSQLState.COMMUNICATION_ERROR);
else if (c == 0)
{
rst[s] = 0;
done = true;
break;
}
else
{
rst[s++] = (byte)c;
}
if (s >= buflen)
{ // Grow the buffer
buflen = (int)(buflen * 2); // 100% bigger
byte[] newrst = new byte[buflen];
System.arraycopy(rst, 0, newrst, 0, s);
rst = newrst;
}
}
}
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", PSQLState.COMMUNICATION_ERROR, e);
}
return encoding.decode(rst, 0, s);
}
/*
* Read a tuple from the back end. A tuple is a two dimensional
* array of bytes
*
* @param nf the number of fields expected
* @param bin true if the tuple is a binary tuple
* @return null if the current response has no more tuples, otherwise
* an array of strings
* @exception SQLException if a data I/O error occurs
*/
public byte[][] ReceiveTupleV3(int nf, boolean bin) throws SQLException
{
//TODO: use l_msgSize
int l_msgSize = ReceiveIntegerR(4);
int i;
int l_nf = ReceiveIntegerR(2);
byte[][] answer = new byte[l_nf][0];
for (i = 0 ; i < l_nf ; ++i)
{
int l_size = ReceiveIntegerR(4);
boolean isNull = l_size == -1;
if (isNull)
answer[i] = null;
else
{
answer[i] = Receive(l_size);
}
}
return answer;
}
/*
* Read a tuple from the back end. A tuple is a two dimensional
* array of bytes
*
* @param nf the number of fields expected
* @param bin true if the tuple is a binary tuple
* @return null if the current response has no more tuples, otherwise
* an array of strings
* @exception SQLException if a data I/O error occurs
*/
public byte[][] ReceiveTupleV2(int nf, boolean bin) throws SQLException
{
int i, bim = (nf + 7) / 8;
byte[] bitmask = Receive(bim);
byte[][] answer = new byte[nf][0];
int whichbit = 0x80;
int whichbyte = 0;
for (i = 0 ; i < nf ; ++i)
{
boolean isNull = ((bitmask[whichbyte] & whichbit) == 0);
whichbit >>= 1;
if (whichbit == 0)
{
++whichbyte;
whichbit = 0x80;
}
if (isNull)
answer[i] = null;
else
{
int len = ReceiveIntegerR(4);
if (!bin)
len -= 4;
if (len < 0)
len = 0;
answer[i] = Receive(len);
}
}
return answer;
}
/*
* Reads in a given number of bytes from the backend
*
* @param siz number of bytes to read
* @return array of bytes received
* @exception SQLException if a data I/O error occurs
*/
public byte[] Receive(int siz) throws SQLException
{
byte[] answer = new byte[siz];
Receive(answer, 0, siz);
return answer;
}
/*
* Reads in a given number of bytes from the backend
*
* @param buf buffer to store result
* @param off offset in buffer
* @param siz number of bytes to read
* @exception SQLException if a data I/O error occurs
*/
public void Receive(byte[] b, int off, int siz) throws SQLException
{
int s = 0;
try
{
while (s < siz)
{
int w = pg_input.read(b, off + s, siz - s);
if (w < 0)
throw new PSQLException("postgresql.stream.eof", PSQLState.COMMUNICATION_ERROR);
s += w;
}
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.ioerror", PSQLState.COMMUNICATION_ERROR, e);
}
}
/*
* This flushes any pending output to the backend. It is used primarily
* by the Fastpath code.
* @exception SQLException if an I/O error occurs
*/
public void flush() throws SQLException
{
try
{
pg_output.flush();
}
catch (IOException e)
{
throw new PSQLException("postgresql.stream.flush", PSQLState.COMMUNICATION_ERROR, e);
}
}
/*
* Closes the connection
*
* @exception IOException if a IO Error occurs
*/
public void close() throws IOException
{
pg_output.close();
pg_input.close();
connection.close();
}
}

View File

@ -1,511 +0,0 @@
/*-------------------------------------------------------------------------
*
* QueryExecutor.java
* Executes a query on the backend.
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/core/QueryExecutor.java,v 1.28 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.core;
import java.util.Vector;
import java.io.IOException;
import java.sql.*;
import org.postgresql.Driver;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
public class QueryExecutor
{
//This version of execute does not take an existing result set, but
//creates a new one for the results of the query
public static BaseResultSet execute(String[] p_sqlFrags,
Object[] p_binds,
BaseStatement statement)
throws SQLException
{
QueryExecutor qe = new QueryExecutor();
qe.m_sqlFrags = p_sqlFrags;
qe.m_binds = p_binds;
qe.statement = statement;
if (statement != null)
qe.maxRows = statement.getMaxRows();
else
qe.maxRows = 0;
qe.connection = statement.getPGConnection();
qe.pgStream = qe.connection.getPGStream();
return qe.execute();
}
//This version of execute reuses an existing result set for the query
//results, this is used when a result set is backed by a cursor and
//more results are fetched
public static void execute(String[] p_sqlFrags,
Object[] p_binds,
BaseResultSet rs)
throws SQLException
{
QueryExecutor qe = new QueryExecutor();
qe.m_sqlFrags = p_sqlFrags;
qe.m_binds = p_binds;
qe.rs = rs;
qe.statement = qe.rs.getPGStatement();
if (qe.statement != null)
qe.maxRows = qe.statement.getMaxRows();
else
qe.maxRows = 0;
qe.connection = qe.statement.getPGConnection();
qe.pgStream = qe.connection.getPGStream();
qe.execute();
}
private QueryExecutor ()
{
}
private String[] m_sqlFrags;
private Object[] m_binds;
private BaseStatement statement;
private BaseResultSet rs;
private BaseConnection connection;
private PGStream pgStream;
private Field[] fields = null;
private Vector tuples = new Vector();
private boolean binaryCursor = false;
private String status = null;
private int update_count = 1;
private long insert_oid = 0;
private int maxRows;
/*
* Execute a query on the backend.
*
*/
private BaseResultSet execute() throws SQLException
{
if (connection.getPGProtocolVersionMajor() == 3) {
if (Driver.logDebug)
Driver.debug("Using Protocol Version3 to send query");
return executeV3();
} else {
if (Driver.logDebug)
Driver.debug("Using Protocol Version2 to send query");
return executeV2();
}
}
private BaseResultSet executeV3() throws SQLException
{
PSQLException error = null;
if (pgStream == null)
{
throw new PSQLException("postgresql.con.closed", PSQLState.CONNECTION_DOES_NOT_EXIST);
}
synchronized (pgStream)
{
sendQueryV3();
int c;
boolean l_endQuery = false;
while (!l_endQuery)
{
c = pgStream.ReceiveChar();
switch (c)
{
case 'A': // Asynchronous Notify
int pid = pgStream.ReceiveInteger(4);
String msg = pgStream.ReceiveString(connection.getEncoding());
connection.addNotification(new org.postgresql.core.Notification(msg, pid));
break;
case 'B': // Binary Data Transfer
receiveTupleV3(true);
break;
case 'C': // Command Status
receiveCommandStatusV3();
break;
case 'D': // Text Data Transfer
receiveTupleV3(false);
break;
case 'E': // Error Message
// it's possible to get more than one error message for a query
// see libpq comments wrt backend closing a connection
// so, append messages to a string buffer and keep processing
// check at the bottom to see if we need to throw an exception
int l_elen = pgStream.ReceiveIntegerR(4);
String totalMessage = connection.getEncoding().decode(pgStream.Receive(l_elen-4));
PSQLException l_error = PSQLException.parseServerError(totalMessage);
if (error != null) {
error.setNextException(l_error);
} else {
error = l_error;
}
// keep processing
break;
case 'I': // Empty Query
int t = pgStream.ReceiveIntegerR(4);
break;
case 'N': // Error Notification
int l_nlen = pgStream.ReceiveIntegerR(4);
statement.addWarning(connection.getEncoding().decode(pgStream.Receive(l_nlen-4)));
break;
case 'P': // Portal Name
String pname = pgStream.ReceiveString(connection.getEncoding());
break;
case 'S':
//TODO: handle parameter status messages
int l_len = pgStream.ReceiveIntegerR(4);
String l_pStatus = connection.getEncoding().decode(pgStream.Receive(l_len-4));
if (Driver.logDebug)
Driver.debug("ParameterStatus="+ l_pStatus);
break;
case 'T': // MetaData Field Description
receiveFieldsV3();
break;
case 'Z':
// read ReadyForQuery
//TODO: use size better
if (pgStream.ReceiveIntegerR(4) != 5) throw new PSQLException("postgresql.con.setup", PSQLState.CONNECTION_UNABLE_TO_CONNECT);
//TODO: handle transaction status
char l_tStatus = (char)pgStream.ReceiveChar();
l_endQuery = true;
break;
default:
throw new PSQLException("postgresql.con.type", PSQLState.CONNECTION_FAILURE, new Character((char) c));
}
}
// did we get an error during this query?
if ( error != null )
throw error;
//if an existing result set was passed in reuse it, else
//create a new one
if (rs != null)
{
rs.reInit(fields, tuples, status, update_count, insert_oid, binaryCursor);
}
else
{
rs = statement.createResultSet(fields, tuples, status, update_count, insert_oid, binaryCursor);
}
return rs;
}
}
private BaseResultSet executeV2() throws SQLException
{
StringBuffer errorMessage = null;
if (pgStream == null)
{
throw new PSQLException("postgresql.con.closed", PSQLState.CONNECTION_DOES_NOT_EXIST);
}
synchronized (pgStream)
{
sendQueryV2();
int c;
boolean l_endQuery = false;
while (!l_endQuery)
{
c = pgStream.ReceiveChar();
switch (c)
{
case 'A': // Asynchronous Notify
int pid = pgStream.ReceiveInteger(4);
String msg = pgStream.ReceiveString(connection.getEncoding());
connection.addNotification(new org.postgresql.core.Notification(msg, pid));
break;
case 'B': // Binary Data Transfer
receiveTupleV2(true);
break;
case 'C': // Command Status
receiveCommandStatusV2();
break;
case 'D': // Text Data Transfer
receiveTupleV2(false);
break;
case 'E': // Error Message
// it's possible to get more than one error message for a query
// see libpq comments wrt backend closing a connection
// so, append messages to a string buffer and keep processing
// check at the bottom to see if we need to throw an exception
if ( errorMessage == null )
errorMessage = new StringBuffer();
errorMessage.append(pgStream.ReceiveString(connection.getEncoding()));
// keep processing
break;
case 'I': // Empty Query
int t = pgStream.ReceiveIntegerR(4);
break;
case 'N': // Error Notification
statement.addWarning(pgStream.ReceiveString(connection.getEncoding()));
break;
case 'P': // Portal Name
String pname = pgStream.ReceiveString(connection.getEncoding());
break;
case 'T': // MetaData Field Description
receiveFieldsV2();
break;
case 'Z':
l_endQuery = true;
break;
default:
throw new PSQLException("postgresql.con.type", PSQLState.CONNECTION_FAILURE, new Character((char) c));
}
}
// did we get an error during this query?
if ( errorMessage != null )
throw new SQLException( errorMessage.toString().trim() );
//if an existing result set was passed in reuse it, else
//create a new one
if (rs != null)
{
rs.reInit(fields, tuples, status, update_count, insert_oid, binaryCursor);
}
else
{
rs = statement.createResultSet(fields, tuples, status, update_count, insert_oid, binaryCursor);
}
return rs;
}
}
/*
* Send a query to the backend.
*/
private void sendQueryV3() throws SQLException
{
for ( int i = 0; i < m_binds.length ; i++ )
{
if ( m_binds[i] == null )
throw new PSQLException("postgresql.prep.param", PSQLState.INVALID_PARAMETER_VALUE, new Integer(i + 1));
}
try
{
byte[][] l_parts = new byte[(m_binds.length*2)+1][];
int j = 0;
int l_msgSize = 4;
Encoding l_encoding = connection.getEncoding();
pgStream.SendChar('Q');
for (int i = 0 ; i < m_binds.length ; ++i)
{
l_parts[j] = l_encoding.encode(m_sqlFrags[i]);
l_msgSize += l_parts[j].length;
j++;
l_parts[j] = l_encoding.encode(m_binds[i].toString());
l_msgSize += l_parts[j].length;
j++;
}
l_parts[j] = l_encoding.encode(m_sqlFrags[m_binds.length]);
l_msgSize += l_parts[j].length;
pgStream.SendInteger(l_msgSize+1,4);
for (int k = 0; k < l_parts.length; k++) {
pgStream.Send(l_parts[k]);
}
pgStream.SendChar(0);
pgStream.flush();
}
catch (IOException e)
{
throw new PSQLException("postgresql.con.ioerror", PSQLState.CONNECTION_FAILURE_DURING_TRANSACTION, e);
}
}
/*
* Send a query to the backend.
*/
private void sendQueryV2() throws SQLException
{
for ( int i = 0; i < m_binds.length ; i++ )
{
if ( m_binds[i] == null )
throw new PSQLException("postgresql.prep.param", PSQLState.INVALID_PARAMETER_VALUE, new Integer(i + 1));
}
try
{
pgStream.SendChar('Q');
for (int i = 0 ; i < m_binds.length ; ++i)
{
pgStream.Send(connection.getEncoding().encode(m_sqlFrags[i]));
pgStream.Send(connection.getEncoding().encode(m_binds[i].toString()));
}
pgStream.Send(connection.getEncoding().encode(m_sqlFrags[m_binds.length]));
pgStream.SendChar(0);
pgStream.flush();
}
catch (IOException e)
{
throw new PSQLException("postgresql.con.ioerror", PSQLState.CONNECTION_FAILURE_DURING_TRANSACTION, e);
}
}
/*
* Receive a tuple from the backend.
*
* @param isBinary set if the tuple should be treated as binary data
*/
private void receiveTupleV3(boolean isBinary) throws SQLException
{
if (fields == null)
throw new PSQLException("postgresql.con.tuple", PSQLState.CONNECTION_FAILURE);
Object tuple = pgStream.ReceiveTupleV3(fields.length, isBinary);
if (isBinary)
binaryCursor = true;
if (maxRows == 0 || tuples.size() < maxRows)
tuples.addElement(tuple);
}
/*
* Receive a tuple from the backend.
*
* @param isBinary set if the tuple should be treated as binary data
*/
private void receiveTupleV2(boolean isBinary) throws SQLException
{
if (fields == null)
throw new PSQLException("postgresql.con.tuple", PSQLState.CONNECTION_FAILURE);
Object tuple = pgStream.ReceiveTupleV2(fields.length, isBinary);
if (isBinary)
binaryCursor = true;
if (maxRows == 0 || tuples.size() < maxRows)
tuples.addElement(tuple);
}
/*
* Receive command status from the backend.
*/
private void receiveCommandStatusV3() throws SQLException
{
//TODO: better handle the msg len
int l_len = pgStream.ReceiveIntegerR(4);
//read l_len -5 bytes (-4 for l_len and -1 for trailing \0)
status = connection.getEncoding().decode(pgStream.Receive(l_len-5));
//now read and discard the trailing \0
pgStream.Receive(1);
try
{
// Now handle the update count correctly.
if (status.startsWith("INSERT") || status.startsWith("UPDATE") || status.startsWith("DELETE") || status.startsWith("MOVE"))
{
update_count = Integer.parseInt(status.substring(1 + status.lastIndexOf(' ')));
}
if (status.startsWith("INSERT"))
{
insert_oid = Long.parseLong(status.substring(1 + status.indexOf(' '),
status.lastIndexOf(' ')));
}
}
catch (NumberFormatException nfe)
{
throw new PSQLException("postgresql.con.fathom", PSQLState.CONNECTION_FAILURE, status);
}
}
/*
* Receive command status from the backend.
*/
private void receiveCommandStatusV2() throws SQLException
{
status = pgStream.ReceiveString(connection.getEncoding());
try
{
// Now handle the update count correctly.
if (status.startsWith("INSERT") || status.startsWith("UPDATE") || status.startsWith("DELETE") || status.startsWith("MOVE"))
{
update_count = Integer.parseInt(status.substring(1 + status.lastIndexOf(' ')));
}
if (status.startsWith("INSERT"))
{
insert_oid = Long.parseLong(status.substring(1 + status.indexOf(' '),
status.lastIndexOf(' ')));
}
}
catch (NumberFormatException nfe)
{
throw new PSQLException("postgresql.con.fathom", PSQLState.CONNECTION_FAILURE, status);
}
}
/*
* Receive the field descriptions from the back end.
*/
private void receiveFieldsV3() throws SQLException
{
//TODO: use the msgSize
//TODO: use the tableOid, and tablePosition
if (fields != null)
throw new PSQLException("postgresql.con.multres", PSQLState.CONNECTION_FAILURE);
int l_msgSize = pgStream.ReceiveIntegerR(4);
int size = pgStream.ReceiveIntegerR(2);
fields = new Field[size];
for (int i = 0; i < fields.length; i++)
{
String typeName = pgStream.ReceiveString(connection.getEncoding());
int tableOid = pgStream.ReceiveIntegerR(4);
int tablePosition = pgStream.ReceiveIntegerR(2);
int typeOid = pgStream.ReceiveIntegerR(4);
int typeLength = pgStream.ReceiveIntegerR(2);
int typeModifier = pgStream.ReceiveIntegerR(4);
int formatType = pgStream.ReceiveIntegerR(2);
//TODO: use the extra values coming back
fields[i] = new Field(connection, typeName, typeOid, typeLength, typeModifier);
}
}
/*
* Receive the field descriptions from the back end.
*/
private void receiveFieldsV2() throws SQLException
{
if (fields != null)
throw new PSQLException("postgresql.con.multres", PSQLState.CONNECTION_FAILURE);
int size = pgStream.ReceiveIntegerR(2);
fields = new Field[size];
for (int i = 0; i < fields.length; i++)
{
String typeName = pgStream.ReceiveString(connection.getEncoding());
int typeOid = pgStream.ReceiveIntegerR(4);
int typeLength = pgStream.ReceiveIntegerR(2);
int typeModifier = pgStream.ReceiveIntegerR(4);
fields[i] = new Field(connection, typeName, typeOid, typeLength, typeModifier);
}
}
}

View File

@ -1,68 +0,0 @@
package org.postgresql.core;
import java.io.IOException;
/**
* Sent to the backend to initialize a newly created connection.
*
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/core/StartupPacket.java,v 1.5 2003/11/29 22:41:22 pgsql Exp $
*/
public class StartupPacket
{
private static final int SM_DATABASE = 64;
private static final int SM_USER = 32;
private static final int SM_OPTIONS = 64;
private static final int SM_UNUSED = 64;
private static final int SM_TTY = 64;
private int protocolMajor;
private int protocolMinor;
private String user;
private String database;
public StartupPacket(int protocolMajor, int protocolMinor, String user, String database)
{
this.protocolMajor = protocolMajor;
this.protocolMinor = protocolMinor;
this.user = user;
this.database = database;
}
public void writeTo(PGStream stream) throws IOException
{
if (protocolMajor == 3) {
v3WriteTo(stream);
} else {
v2WriteTo(stream);
}
}
public void v3WriteTo(PGStream stream) throws IOException
{
stream.SendInteger(4 + 4 + "user".length() + 1 + user.length() + 1 + "database".length() +1 + database.length() + 1 + 1, 4);
stream.SendInteger(protocolMajor, 2);
stream.SendInteger(protocolMinor, 2);
stream.Send("user".getBytes());
stream.SendChar(0);
stream.Send(user.getBytes());
stream.SendChar(0);
stream.Send("database".getBytes());
stream.SendChar(0);
stream.Send(database.getBytes());
stream.SendChar(0);
stream.SendChar(0);
}
public void v2WriteTo(PGStream stream) throws IOException
{
stream.SendInteger(4 + 4 + SM_DATABASE + SM_USER + SM_OPTIONS + SM_UNUSED + SM_TTY, 4);
stream.SendInteger(protocolMajor, 2);
stream.SendInteger(protocolMinor, 2);
stream.Send(database.getBytes(), SM_DATABASE);
// This last send includes the unused fields
stream.Send(user.getBytes(), SM_USER + SM_OPTIONS + SM_UNUSED + SM_TTY);
}
}

View File

@ -1,112 +0,0 @@
# This is the default errors
postgresql.arr.range:The array index is out of range.
postgresql.drv.version:An internal error has occured. Please recompile the driver.
postgresql.con.auth:The authentication type {0} is not supported. Check that you have configured the pg_hba.conf file to include the client's IP address or Subnet, and that it is using an authentication scheme supported by the driver.
postgresql.con.authfail:An error occured while getting the authentication request.
postgresql.con.backend:Backend start-up failed: {0}
postgresql.con.call:Callable Statements are not supported at this time.
postgresql.con.invalidchar:Invalid character data was found. This is most likely caused by stored data containing characters that are invalid for the character set the database was created in. The most common example of this is storing 8bit data in a SQL_ASCII database.
postgresql.con.closed:Connection is closed. Operation is not permitted.
postgresql.con.creobj:Failed to create object for {0} {1}
postgresql.con.failed:The connection attempt failed because {0}
postgresql.con.failed.bad.encoding:The connection attempt failed trying to get the server encoding
postgresql.con.failed.bad.autocommit:The connection attempt failed trying to get the autocommit status
postgresql.con.fathom:Unable to fathom update count {0}
postgresql.con.garbled:Garbled data received.
postgresql.con.ioerror:An IO erro occured while sending to the backend - {0}
postgresql.con.kerb4:Kerberos 4 authentication is not supported by this driver.
postgresql.con.kerb5:Kerberos 5 authentication is not supported by this driver.
postgresql.con.misc:A connection error has occurred: {0}
postgresql.con.multres:Cannot handle multiple result groups.
postgresql.con.pass:The password property is missing. It is mandatory.
postgresql.con.refused:Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
postgresql.con.scm:SCM credentials authentication is not supported by this driver.
postgresql.con.setup:Protocol error. Session setup failed.
postgresql.con.sslfail:An error occured while getting setting up the SSL connection.
postgresql.con.sslnotsupported:The server does not support SSL
postgresql.con.strobj:The object could not be stored. Check that any tables required have already been created in the database.
postgresql.con.strobjex:Failed to store object - {0}
postgresql.con.toolong:The SQL Statement is too long - {0}
postgresql.con.isolevel:Transaction isolation level {0} is not supported.
postgresql.con.tuple:Tuple received before MetaData.
postgresql.con.type:Unknown Response Type {0}
postgresql.con.user:The user property is missing. It is mandatory.
postgresql.error.detail:Detail: {0}
postgresql.error.hint:Hint: {0}
postgresql.error.position:Position: {0}
postgresql.error.where:Where: {0}
postgresql.error.location:Location: {0}
postgresql.fp.error:FastPath call returned {0}
postgresql.fp.expint:Fastpath call {0} - No result was returned and we expected an integer.
postgresql.fp.protocol:FastPath protocol error: {0}
postgresql.fp.send:Failed to send fastpath call {0} {1}
postgresql.fp.unknown:The fastpath function {0} is unknown.
postgresql.geo.box:Conversion of box failed - {0}
postgresql.geo.circle:Conversion of circle failed - {0}
postgresql.geo.line:Conversion of line failed - {0}
postgresql.geo.lseg:Conversion of lseg failed - {0}
postgresql.geo.path:Cannot tell if path is open or closed.
postgresql.geo.point:Conversion of point failed - {0}
postgresql.jvm.version:The postgresql.jar file does not contain the correct JDBC classes for this JVM. Try rebuilding. If that fails, try forcing the version supplying it to the command line using the argument -Djava.version=1.1 or -Djava.version=1.2\nException thrown was {0}
postgresql.lo.init:failed to initialise LargeObject API
postgresql.metadata.unavailable:Metadata unavailable.
postgresql.money:conversion of money failed - {0}
postgresql.noupdate:This ResultSet is not updateable.
postgresql.notsensitive:This ResultSet is not sensitive to realtime updates after the query has run.
postgresql.psqlnotimp:The backend currently does not support this feature.
postgresql.prep.is:InputStream as parameter not supported
postgresql.prep.param:No value specified for parameter {0}
postgresql.prep.range:Parameter index out of range.
postgresql.prep.type:Unknown Types value.
postgresql.res.badbigdec:Bad BigDecimal {0}
postgresql.res.badbyte:Bad Byte {0}
postgresql.res.baddate:Bad Date Format at {0} in {1}
postgresql.res.baddouble:Bad Double {0}
postgresql.res.badfloat:Bad Float {0}
postgresql.res.badint:Bad Integer {0}
postgresql.res.badlong:Bad Long {0}
postgresql.res.badshort:Bad Short {0}
postgresql.res.badtime:Bad Time {0}
postgresql.res.badtimestamp:Bad Timestamp Format at {0} in {1}
postgresql.res.closed:Result set is closed. Operation is not permitted.
postgresql.res.colname:The column name {0} not found.
postgresql.res.colrange:The column index is out of range.
postgresql.res.nextrequired:Result set not positioned properly, perhaps you need to call next().
postgresql.serial.interface:You cannot serialize an interface.
postgresql.serial.namelength:Class & Package name length cannot be longer than 64 characters. {0} is {1} characters.
postgresql.serial.noclass:No class found for {0}
postgresql.serial.table:The table for {0} is not in the database. Contact the DBA, as the database is in an inconsistent state.
postgresql.serial.underscore:Class names may not have _ in them. You supplied {0}.
postgresql.stat.batch.error:Batch entry {0} {1} was aborted. Call getNextException() to see the cause.
postgresql.stat.noresult:No results were returned by the query.
postgresql.stat.result:A result was returned when none was expected.
postgresql.stream.eof:The backend has broken the connection. Possibly the action you have attempted has caused it to close.
postgresql.stream.flush:An I/O error has occured while flushing the output - {0}
postgresql.stream.ioerror:An I/O error occured while reading from backend - {0}
postgresql.stream.toomuch:Too much data was received.
postgresql.unusual:Something unusual has occured to cause the driver to fail. Please report this exception: {0}
postgresql.unimplemented:This method is not yet implemented.
postgresql.unexpected:An unexpected result was returned by a query.
postgresql.updateable.notupdateable: Result Set not updateable. The query that generated this result set must select only one table, and must select all primary keys from that table. See the JDBC 2.1 API Specification, section 5.6 for more details.
postgresql.updateable.oninsertrow:Can not call deleteRow() when on insert row
postgresql.updateable.emptydelete:Can't deleteRow() on empty result set
postgresql.updateable.beforestartdelete:Before start of result set. Can not call deleteRow().
postgresql.updateable.afterlastdelete:After end of result set. Can not call deleteRow().
postgresql.updateable.notoninsertrow:Not on insert row.
postgresql.updateable.inputstream:Input Stream is null.
postgresql.updateable.ioerror:Input Stream Error - {0}
postgresql.call.noreturntype:A CallableStatement Function was declared but no call to 'registerOutParameter (1, <some_type>)' was made.
postgresql.call.noinout:PostgreSQL only supports function return value [@ 1] (no OUT or INOUT arguments)
postgresql.call.procasfunc:This Statement [{0}] defines a procedure call (needs ?= call <stmt> to be considered a function.
postgresql.call.malformed:Malformed stmt [{0}] usage : {1}
postgresql.call.funcover:Cannot execute Query a call to setXXX (1, ..) was made where argument 1 is the return value of a function.
postgresql.call.wrongget:Parameter of type {0} was registered but call to get{1} (sqltype={2}) was made.
postgresql.call.noreturnval:A CallableStatement Function was executed with nothing returned.
postgresql.call.wrongrtntype:A CallableStatement Function was executed and the return was of type ({0}) however type={1} was registered.
postgresql.input.fetch.gt0:Fetch size must be a value greater than or equal to 0.
postgresql.input.query.gt0:Query Timeout must be a value greater than or equal to 0.
postgresql.input.rows.gt0:Maximum number of rows must be a value greater than or equal to 0.
postgresql.format.baddate:The date given: {0} does not match the format required: {1}.
postgresql.format.badtime:The time given: {0} does not match the format required: {1}.
postgresql.format.badtimestamp:The timestamp given {0} does not match the format required: {1}.
postgresql.input.field.gt0:The maximum field size must be a value greater than or equal to 0.

View File

@ -1,78 +0,0 @@
# Message translation file for PostgreSQL JDBC driver
# Peter Eisentraut <peter_e@gmx.net>, 2001.
#
# $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/errors_de.properties,v 1.6 2003/11/29 19:52:09 pgsql Exp $
postgresql.con.auth:Der Authentifizierungstyp »{0}« wird nicht unterstützt.
postgresql.con.authfail:Ein Fehler trat auf während die Authentifizierungsanfrage empfangen wurde.
postgresql.con.call:CallableStatement wird nicht unterstützt.
postgresql.con.creobj:Konnte Objekt vom Typ {0} nicht erstellen: {1}
postgresql.con.encoding:Nicht unterstützte Kodierung: {0}
postgresql.con.failed:Der Verbindungsversuch schlug fehl: {0}
postgresql.con.fathom:Kann Anzahl der veränderten Zeilen nicht ermitteln: {0}
postgresql.con.garbled:Unverständliche Daten wurden empfangen.
postgresql.con.ioerror:Eingabe/Ausgabe-Fehler: {0}
postgresql.con.isolevel:Transaktionsisolation {0} wird nicht unterstützt.
postgresql.con.kerb4:Kerberos-IV-Authentifizierung wird von diesem Treiber nicht unterstützt.
postgresql.con.kerb5:Kerberos-V-Authentifizierung wird von diesem Treiber nicht unterstützt.
postgresql.con.multres:Mehrere Ergebnisgruppen können nicht verarbeitet werden.
postgresql.con.pass:Das Paßwort fehlt.
postgresql.con.refused:Verbindung verweigert. Prüfen Sie, daß der Server TCP/IP-Verbindungen annimmt.
postgresql.con.setup:Protokollfehler - Sitzung konnte nicht gestartet werden.
postgresql.con.strobj:Konnte Objekt nicht speichern - {0}
postgresql.con.strobjex:Das Objekt konnte nicht gespeichert werden. Prüfen Sie, daß die benötigten Tabellen bereits erstellt wurden.
postgresql.con.tuple:Ergebnisdaten wurden empfangen, als sie nicht erwartet wurden.
postgresql.con.type:Unbekannte Antwort vom Server: »{0}«
postgresql.con.user:Benutzername wurde nicht angegeben.
postgresql.ds.onlyjdbc2:Es werden nur JDBC2-Verbindungen unterstützt.
postgresql.ds.userpswd:Kein Benutzername oder Paßwort angegeben.
postgresql.fp.error:FastPath-Aufruf ergab »{0}«.
postgresql.fp.expint:FastPath-Aufruf »{0}« gab kein Ergebnis zurück, aber ein Integer wurde erwartet.
postgresql.fp.protocol:FastPath-Protokollfehler: {0}
postgresql.fp.send:Konnte FastPath-Aufruf »{0}« nicht senden: {1}
postgresql.fp.unknown:Die FastPath-Funktion »{0}« ist nicht bekannt.
postgresql.geo.box:Konnte »{0}« nicht in Typ »box« umwandeln
postgresql.geo.circle:Konnte »{0}« nicht in Typ »circle« umwandeln
postgresql.geo.line:Konnte »{0}« nicht in Typ »line« umwandeln
postgresql.geo.lseg:Konnte »{0}« nicht in Typ »lseg« umwandeln
postgresql.geo.path:Konnte nicht in Typ »path« umwandeln - konnte nicht ermitteln ob der Pfad offen oder geschlossen ist
postgresql.geo.point:Konnte »{0}« nicht in Typ »point« umwandeln
postgresql.jvm.version:Die Datei postgresql.jar enthält nicht die benötigten Klassen für diese JVM-Version. Versuchen Sie, den Treiber neu zu übersetzen. Falls das nicht hilft, bestimmen Sie die Version mit den Kommandozeilenoptionen -Djava.version=1.1 oder -Djava.version=1.2. Der Fehler war »{0}«
postgresql.lo.init:Konnte Large-Object-API nicht initialisieren.
postgresql.money:Ungültiges Format für Typ »money«: {0}
postgresql.notsensitive:Dieses ResultSet ermöglicht keine Auffrischungen nach der Abfrage.
postgresql.noupdate:Dieses ResultSet kann nicht verändert werden.
postgresql.prep.is:InputStream als Parameter wird nicht unterstützt.
postgresql.prep.param:Keinen Wert für Parameter {0} angegeben
postgresql.prep.range:Parameterindex außerhalb des gültigen Bereichs
postgresql.prep.type:Unbekannter Zieltyp
postgresql.psqlnotimp:Der Server unterstützt diese Funktion nicht.
postgresql.res.badbigdec:Ungültiges Format für BigDecimal: {0}
postgresql.res.badbyte:Ungültiges Format für Byte: {0}
postgresql.res.baddate:Ungültiger Datumswert »{0}«
postgresql.res.baddouble:Ungültiges Format für Double: {0}
postgresql.res.badfloat:Ungültiges Format für Float: {0}
postgresql.res.badint:Ungültiges Format für Integer: {0}
postgresql.res.badlong:Ungültiges Format für Long: {0}
postgresql.res.badshort:Ungültiges Format für Short: {0}
postgresql.res.badtime:Ungültiger Zeitwert »{0}«
postgresql.res.badtimestamp:Ungültiger Wert für Timestamp (Datum und Zeit), in »{1}« bei Position {1}
postgresql.res.colname:Spaltenname »{0}« nicht gefunden
postgresql.res.colrange:Spaltenindex außerhalb des gültigen Bereichs
postgresql.res.encoding:Nicht unterstützte Kodierung: {0}
postgresql.serial.interface:Ein Interface kann nicht serialisiert werden.
postgresql.serial.namelength:Klassen- und Paketname können nicht länger als 32 Zeichen sein. »{0}« ist {1} Zeichen lang.
postgresql.serial.noclass:Keine Klasse für Typ »{0}« gefunden
postgresql.serial.table:Keine Tabelle für Typ »{0}« in der Datenbank gefunden. Die Datenbank ist in einem unbeständigen Zustand.
postgresql.serial.underscore:Zu serialisierende Klassennamen dürfen keine Unterstriche (_) enthälten. Der angegebene Name war »{0}«.
postgresql.stat.batch.error:Batch-Anweisung Nummer {0} ({1}) wurde abgebrochen.
postgresql.stat.noresult:Die Abfrage ergab kein Ergebnis.
postgresql.stat.result:Die Anweisung ergab einen Abfrageergebnissatz, obwohl keiner erwartet wurde.
postgresql.stream.encoding:Nicht unterstützte Kodierung: {0}
postgresql.stream.eof:Unerwarteter Verbindungsabbruch vom Server
postgresql.stream.flush:Eingabe/Ausgabe-Fehler beim Flush zum Server: {0}
postgresql.stream.ioerror:Eingabe/Ausgabe-Fehler beim Empfang vom Server: {0}
postgresql.stream.toomuch:Zu viele Daten wurden empfangen.
postgresql.unexpected:Ein unerwartetes Resultat wurde nach einer Abfrage zurückgesendet.
postgresql.unimplemented:Diese Methode ist noch nicht implementiert.
postgresql.unusual:Etwas ungewöhnliches ist passiert. Bitte Teilen Sie diesem Fehler mit: {0}

View File

@ -1,6 +0,0 @@
# This is the french version of some errors. Errors not in this file
# are handled by the parent errors.properties file.
postgresql.jvm.version:Le fichier de postgresql.jar ne contient pas les classes correctes de JDBC pour ce JVM. Try que rebuilding.\nException jet<65>ées <20>était {0}
postgresql.metadata.unavailable: Les métadonnées ne sont pas disponibles.
postgresql.unusual:Quelque chose de peu commun s'est produit pour faire <20>échouer le gestionnaire. Veuillez enregistrer cette exception: {0}
postgresql.unimplemented:Cette m<>éthode n'est pas encore appliqu<71>ée.

View File

@ -1,75 +0,0 @@
# This is the italian version of some errors. Errors not in this file
# are handled by the parent errors.properties file.
#
# Daniele Arduini <darduini@cinetica.it <mailto:darduini@cinetica.it>>
# Tue Aug 21 09:26:47 CEST 2001
#
postgresql.drv.version:Si è verificato un errore interno. Si consiglia di ricompilare il driver.
postgresql.con.auth:L'autenticazione di tipo {0} non è supportata. Verificare che nel file di configurazione pg_hba.conf sia presente l'indirizzo IP o la sotto-rete del client, e che lo schema di autenticazione utilizzato sia supportato dal driver.
postgresql.con.authfail:Si è verificato un errore durante la richiesta di autenticazione.
postgresql.con.call:I ``Callable Statements'' non sono supportati al momento.
postgresql.con.creobj:Fallita la creazione dell'oggetto per {0} {1}
postgresql.con.failed:Il tentativo di connessione è fallito perché {0}
postgresql.con.fathom:Impossibile il conteggio di ``update'' {0}
postgresql.con.garbled:Ricevuti dati incomprensibili.
postgresql.con.ioerror:Si è verificato un errore di I/O nella spedizione di dati al processo server - {0}
postgresql.con.kerb4:L'autenticazione di tipo ``Kerberos 4'' non è supportata da questo driver.
postgresql.con.kerb5:L'autenticazione di tipo ``Kerberos 5'' non è supportata da questo driver.
postgresql.con.multres:Impossibile gestire gruppi multipli di risultati.
postgresql.con.pass:La proprietà ``password'' è mancante. E` obbligatoria.
postgresql.con.refused:Connessione rifiutata. Controllare che il nome dell'host e la porta siano corretti, e che il server (postmaster) è in esecuzione con l'opzione -i, che abilita le connessioni attraverso la rete TCP/IP.
postgresql.con.setup:Errore di protocollo. Fallita l'impostazione della sessione.
postgresql.con.strobj:L'oggetto potrebbe non essere stato memorizzato. Controllare che ogni tabella richiesta è stata creata nel database.
postgresql.con.strobjex:Fallita la memorizzazione dell'oggetto - {0}
postgresql.con.toolong:L'istruzione SQL è troppo lunga - {0}
postgresql.con.isolevel:Il livello d'isolamento delle transazioni {0} non è supportato.
postgresql.con.tuple:Tupla ricevuta prima del MetaData.
postgresql.con.type:Tipo di risposta sconosciuta {0}
postgresql.con.user:La proprietà ``user'' è mancante. E` obbligatoria.
postgresql.fp.error:La chiamata a FastPath ha restituito {0}
postgresql.fp.expint:Chiamata Fastpath {0} - Nessun risultato restituito mentre ci si aspettava un intero.
postgresql.fp.protocol:Errore nel protocollo FastPath: {0}
postgresql.fp.send:Fallito l'invio della chiamata fastpath {0} {1}
postgresql.fp.unknown:La funzione fastpath {0} è sconosciuta.
postgresql.geo.box:Fallita la conversione di un ``box'' - {0}
postgresql.geo.circle:Fallita la conversione di un ``circle'' - {0}
postgresql.geo.line:Fallita la conversione di una ``line'' - {0}
postgresql.geo.lseg:Fallita la conversione di un ``lseg'' - {0}
postgresql.geo.path:Impossibile stabilire se il percorso è aperto o chiuso.
postgresql.geo.point:Fallita la conversione di un ``point'' - {0}
postgresql.jvm.version:Il file ``postgresql.jar'' non contiene le classi JDBC corrette per questa JVM. Provare a ricompilarle. Se il problema persiste, tentare di forzare la versione fornendo sulla linea di comando l'opzione -Djava.version=1.1 oppure -Djava.version=1.2\nL'eccezione ricevuta è stata {0}
postgresql.lo.init:Inizializzazione di LargeObject API fallita.
postgresql.money:Fallita la conversione di un ``money'' - {0}.
postgresql.noupdate:Questo ResultSet non è modificabile.
postgresql.notsensitive:Questo ResultSet non risente delle modifiche in tempo reale dopo che la query è stata eseguita.
postgresql.psqlnotimp:Il processo server al momento non supporta questa funzionalità.
postgresql.prep.is:InputStream come parametro non è supportato
postgresql.prep.param:Nessun valore specificato come parametro {0}.
postgresql.prep.range:Indice del parametro fuori dall'intervallo ammissibile.
postgresql.prep.type:Valore di tipo sconosciuto.
postgresql.res.badbigdec:BigDecimal non corretto {0}
postgresql.res.badbyte:Byte non corretto {0}
postgresql.res.baddate:Date Format non corretto a {0} in {1}
postgresql.res.baddouble:Double non corretto {0}
postgresql.res.badfloat:Float non corretto {0}
postgresql.res.badint:Integer non corretto {0}
postgresql.res.badlong:Long non corretto {0}
postgresql.res.badshort:Short non corretto {0}
postgresql.res.badtime:Time non corretto {0}
postgresql.res.badtimestamp:Timestamp Format non corretto a {0} in {1}
postgresql.res.colname:Colonna denominata {0} non trovata.
postgresql.res.colrange:Indice di colonna fuori dall'intervallo ammissibile.
postgresql.serial.interface:Impossibile serializzare un'interfaccia.
postgresql.serial.namelength:La lunghezza dei nomi per Class & Package non può essere superiore a 32 caratteri. {0} è di {1} caratteri.
postgresql.serial.noclass:Nessuna classe trovata per {0}.
postgresql.serial.table:La tabella per {0} non è nel database. Contattare l'amministratore del DB, visto che il database è in uno stato incosistente.
postgresql.serial.underscore:Il nome di una classe non può contenere il carattere ``_''. E` stato fornito {0}.
postgresql.stat.batch.error:L'operazione {0} {1} della sequenza è stata annullata.
postgresql.stat.noresult:Nessun risultato è stato restituito dalla query.
postgresql.stream.eof:Il backend ha interrotto la connessione. Probabilmente la tua azione ha causato la sua uscita.
postgresql.stream.flush:Si è verificato un errore di I/O mentre si svuotava il buffer d'uscita - {0}
postgresql.stream.ioerror:Si è verificato un errore di I/O mentre si leggevano dati dal backend - {0}
postgresql.stream.toomuch:Troppi dati ricevuti.
postgresql.unusual:Qualcosa di insolito si è verificato causando il fallimento del driver. Per favore riferire all'autore del driver questa eccezione: {0}
postgresql.unimplemented:Questo metodo non è stato ancora implementato.
postgresql.unexpected:Un risultato inaspettato è stato ricevuto dalla query.

View File

@ -1,65 +0,0 @@
# This is the default errors
# Dutch translation by Arnout Kuiper (ajkuiper@wxs.nl)
postgresql.con.auth:Het authenticatie type {0} wordt niet ondersteund. Controleer dat het IP adres of subnet van de client is geconfigureerd in de pg_hba.conf file, en dat het een authenticatie protocol gebruikt dat door de driver ondersteund wordt.
postgresql.con.authfail:Een fout trad op tijdens het ophalen van het authenticatie verzoek.
postgresql.con.call:Callable Statements worden op dit moment niet ondersteund.
postgresql.con.creobj:Kon geen object aanmaken voor {0} {1}
postgresql.con.failed:De poging om verbinding the maken faalde omdat {0}
postgresql.con.fathom:Niet in staat om the update telling te peilen {0}
postgresql.con.garbled:Verminkte data ontvangen.
postgresql.con.ioerror:Een I/O fout trad op tijdens het zenden naar de achterkant - {0}
postgresql.con.kerb4:Kerberos 4 authenticatie wordt niet ondersteund door deze driver.
postgresql.con.kerb5:Kerberos 5 authenticatie wordt niet ondersteund door deze driver.
postgresql.con.multres:Kan niet omgaan met meerdere resultaat groepen.
postgresql.con.pass:Het password, welke verplicht is, ontbreekt.
postgresql.con.refused:Verbinding geweigerd. Controleer dat de hostnaam en poort correct zijn, en dat de postmaster is opgestart met de -i vlag, welke TCP/IP networking aanzet.
postgresql.con.strobj:Het object kon niet worden opgeslagen. Controleer dat alle benodigde tabellen aangemaakt zijn in de database.
postgresql.con.strobjex:Kon niet object opslaan - {0}
postgresql.con.toolong:Het SQL Statement is te lang - {0}
postgresql.con.tuple:Tuple ontvangen voor MetaData.
postgresql.con.type:Onbekend antwoord type {0}
postgresql.con.user:De user, welke verplicht is, ontbreekt.
postgresql.fp.error:FastPath aanroep retourneerde {0}
postgresql.fp.expint:Fastpath aanroep {0} - Geen resultaat werd teruggegeven, terwijl we een integer verwacht hadden.
postgresql.fp.protocol:FastPath protocol fout: {0}
postgresql.fp.send:Kon geen fastpath aanroep verzenden {0} {1}
postgresql.fp.unknown:De fastpath functie {0} is onbekend.
postgresql.geo.box:Conversie van box faalde - {0}
postgresql.geo.circle:Conversie van circle faalde - {0}
postgresql.geo.line:Conversie van line faalde - {0}
postgresql.geo.lseg:Conversie van lseg faalde - {0}
postgresql.geo.path:Kan niet zeggen of path open of gesloten is.
postgresql.geo.point:Conversie van point faalde - {0}
postgresql.jvm.version:De postgresql.jar file bevat niet de correcte JDBC classen voor deze JVM. Probeer opnieuw te bouwen. Als dat niet werkt, probeer de versie te forceren via de command line met het argument -Djava.version=1.1 of -Djava.version=1.2\nAfgevuurde exceptie was {0}
postgresql.lo.init:Kon LargeObject API niet initialiseren
postgresql.money:Conversie van money faalde - {0}.
postgresql.prep.is:InputStream als parameter wordt niet ondersteund
postgresql.prep.param:Geen waarde opgegeven voor parameter {0}.
postgresql.prep.range:Parameterindex is buiten bereik.
postgresql.prep.type:Onbekende Types waarde.
postgresql.res.badbigdec:Foute BigDecimal {0}
postgresql.res.badbyte:Foute Byte {0}
postgresql.res.baddate:Foutief Date Formaat op {0} in {1}
postgresql.res.baddouble:Foute Double {0}
postgresql.res.badfloat:Foute Float {0}
postgresql.res.badint:Foute Integer {0}
postgresql.res.badlong:Foute Long {0}
postgresql.res.badshort:Foute Short {0}
postgresql.res.badtime:Foute Time {0}
postgresql.res.badtimestamp:Foutief Timestamp Formaat op {0} in {1}
postgresql.res.colname:De kolom naam {0} is niet gevonden.
postgresql.res.colrange:De kolom index is buiten bereik.
postgresql.serial.interface:Je can geen interface serializeren.
postgresql.serial.namelength:Class & Package name length cannot be longer than 32 characters. {0} is {1} characters.
postgresql.serial.noclass:Geen class gevonden voor {0}.
postgresql.serial.table:De tabel voor {0} is niet in de database. Neem contact op met de DBA, omdat de database in een inconsistente staat verkeert.
postgresql.serial.underscore:Class namen mogen geen _ in zich hebben. Jij voerde {0} in.
postgresql.stat.batch.error:Batch invoer {0} {1} werd afgebroken.
postgresql.stat.noresult:Geen resultaten werden teruggegeven door de query.
postgresql.stream.eof:De achterkant heeft de verbinding verbroken. Mogelijk was de actie die je probeerde de oorzaak hiervan.
postgresql.stream.flush:Een I/O fout trad op tijdens het legen van de uitvoer - {0}
postgresql.stream.ioerror:Een I/O fout trad op tijdens het lezen van de achterkant - {0}
postgresql.stream.toomuch:Teveel gegevens werden ontvangen
postgresql.unusual:Iets ongewoons is opgetreden, wat deze driver doet falen. Rapporteer deze fout AUB: {0}
postgresql.unimplemented:Deze methode is nog niet geimplementeerd
postgresql.unexpected:Een onverwacht resultaat werd teruggegeven door een query

View File

@ -1,113 +0,0 @@
# Polish translation of error messages.
# Translated by Piotr Maj <piotr.maj@kernelpanic.pl>
postgresql.arr.range:Indeks tablicy jest poza zakresem.
postgresql.drv.version:Wyst\u0105pi\u0142 b\u0142\u0105d wewn\u0119trzny. Prosz\u0119 przekompilowa\u0107 sterownik.
postgresql.con.auth:Typ autentykacji {0} nie jest obs\u0142ugiwany. Upewnij si\u0119, \u017ce skonfigurowa\u0142e\u015b plik pg_hba.conf tak, \u017ce zawiera on adres IP lub podsie\u0107 klienta oraz \u017ce u\u017cyta metoda authentykacji jest wspierana przez ten sterownik.
postgresql.con.authfail:Wyst\u0105pi\u0142 b\u0142\u0105d podczas odbierania \u017c\u0105dania autentykacji.
postgresql.con.backend:Start serwera si\u0119 nie powi\u00f3d\u0142: {0}
postgresql.con.call:Callable Statements nie s\u0105 jeszcze obs\u0142ugiwane.
postgresql.con.invalidchar:Znaleziono nieprawid\u0142owy znak. Najprawdopodobniej jest to spowodowane przechowywaniem w bazie znak\u00f3w, kt\u00f3re nie pasuj\u0105 do zestawu znak\u00f3w wybranego podczas tworzenia bazy danych. Najcz\u0119stszy przyk\u0142ad to przechowywanie 8-bitowych znak\u00f3w w bazie o kodowaniu SQL_ASCII.
postgresql.con.closed:Po\u0142\u0105czenie jest zamkni\u0119te. Operacja nie dozwolona.
postgresql.con.creobj:Utworzenie obiektu dla {0} {1} nie powiod\u0142o si\u0119.
postgresql.con.failed:Pr\u00f3ba nawi\u0105zania po\u0142\u0105czenia nie powiod\u0142a si\u0119 z powodu: {0}
postgresql.con.failed.bad.encoding:Pr\u00f3ba nawi\u0105zania po\u0142aczenia nie powiod\u0142a si\u0119 - nie mo\u017cna uzyska\u0107 strony kodowej serwera.
postgresql.con.failed.bad.autocommit:Pr\u00f3ba nawi\u0105zania po\u0142\u0105czenia nie powiod\u0142a si\u0119 - nie mo\u017cna uzyska\u0107 statusu autocommit.
postgresql.con.fathom:Nie mo\u017cna wysondowa\u0107 ilo\u015bci rekord\u00f3w {0}
postgresql.con.garbled:Otrzymano przek\u0142amane dane.
postgresql.con.ioerror:Wyst\u0105pi\u0142 b\u0142\u0105d IO podczas wysy\u0142ania do serwera - {0}
postgresql.con.kerb4:Autentykacja Kerberos 4 nie jest wspierana przez ten sterownik.
postgresql.con.kerb5:Autentykacja 5 nie jest wspierana przez ten sterownik.
postgresql.con.misc:Wyst\u0105pi\u0142 b\u0142\u0105d po\u0142\u0105czenia: {0}
postgresql.con.multres:Nie mo\u017cna stosowa\u0107 wielokrotnych grup wynik\u00f3w.
postgresql.con.pass:Brak has\u0142a (password property). Jest to wymagane.
postgresql.con.refused:Po\u0142\u0105czenie odrzucone. Sprawd\u017a, czy prawid\u0142owo ustawi\u0142e\u015b nazw\u0119 hosta oraz port i upewnij si\u0119, czy postmaster przyjmuje po\u0142\u0105czenia TCP/IP.
postgresql.con.scm:Autentykacja SCM credentials nie jest wspierana przez ten sterownik.
postgresql.con.setup:B\u0142\u0105d protoko\u0142u. Nie uda\u0142o si\u0119 utworzy\u0107 sesji.
postgresql.con.sslfail:Wyst\u0105pi\u0142 b\u0142\u0105d podczas ustanawiania po\u0142\u0105czenia SSL.
postgresql.con.sslnotsupported:Serwer nie obs\u0142uguje SSL.
postgresql.con.strobj:Nie uda\u0142o si\u0119 zapisa\u0107 objektu. Sprawd\u017a, czy niekt\u00f3re wymagane tabele nie zosta\u0142y ju\u017c utworzone w bazie danych.
postgresql.con.strobjex:Nie uda\u0142o sie zapisa\u0107 obiektu - {0}
postgresql.con.toolong:Zapytanie SQL jest zbyt d\u0142ugie - {0}
postgresql.con.isolevel:Poziom izolacji transakcji {0} nie jest obs\u0142ugiwany.
postgresql.con.tuple:Odebrano krotk\u0119 przed MetaData.
postgresql.con.type:Nieznany typ odpowiedzi {0}
postgresql.con.user:Nie zdefiniowano u\u017cytkownika (user property). Jest to wymagane.
postgresql.error.detail:Szczeg\u00f3\u0142y: {0}
postgresql.error.hint:Wskaz\u00f3wka: {0}
postgresql.error.position:Pozycja: {0}
postgresql.error.where:Gdzie: {0}
postgresql.error.location:Lokalizacja: {0}
postgresql.fp.error:Wywo\u0142anie FastPath zwr\u00f3ci\u0142o {0}
postgresql.fp.expint:Wywo\u0142anie FastPath {0} - Nie otrzymano \u017cadnego wyniku, a oczekiwano liczby ca\u0142kowitej.
postgresql.fp.protocol:B\u0142\u0105d protoko\u0142u FastPath: {0}
postgresql.fp.send:Nie uda\u0142o si\u0119 wys\u0142a\u0107 wywo\u0142ania FastPath {0} {1}
postgresql.fp.unknown:Funkcja FastPath {0} jest nieznana.
postgresql.geo.box:Konwersja typu box nie powiod\u0142a si\u0119 - {0}
postgresql.geo.circle:Konwersja typu circle nie powiod\u0142a si\u0119 - {0}
postgresql.geo.line:Konwersja typu line nie powiod\u0142a si\u0119 - {0}
postgresql.geo.lseg:Konwersja typu lseg nie powiod\u0142a si\u0119 - {0}
postgresql.geo.path:Nie mo\u017cna stwierdzi\u0107, czy \u015bcie\u017cka jest otwarta czy zamkni\u0119ta.
postgresql.geo.point:Konwersja typu point nie powiod\u0142a si\u0119 - {0}
postgresql.jvm.version: Plik postgresql.jar nie zawiera poprawnych klas JDBC dla tej JVM. Spr\u00f3buj przekompilowa\u0107 sterownik. Je\u017celi si\u0119 to nie uda spr\u00f3buj wymusi\u0107 wersj\u0119 przez podanie jej w linii polece\u0107 jako argument -Djava.version=1.1 lub -Djava.version=1.2\nZrzucony wyj\u0105tek to {0}
postgresql.lo.init:nie uda\u0142o si\u0119 zainicjowa\u0107 LargeObject API
postgresql.metadata.unavailable:Metadata nie dost\u0119pne.
postgresql.money:Konwersja typu money nie powiod\u0142a si\u0119 - {0}
postgresql.noupdate:Ten ResultSet jest niemodyfikowalny (not updateable).
postgresql.notsensitive:Ten ResultSet nie jest wra\u017cliwy na zmiany w czasie rzeczywistym po tym, jak zapytanie si\u0119 wykona\u0142o.
postgresql.psqlnotimp:Serwer aktualnie nie obs\u0142uguje tej funkcji.
postgresql.prep.is:InputStream jako parametr nie jest obs\u0142ugiwany.
postgresql.prep.param:Nie podano warto\u015bci dla parametru {0}
postgresql.prep.range:Indeks parametru poza zakresem.
postgresql.prep.type:Nieznana warto\u015b\u0107 Types.
postgresql.res.badbigdec:Z\u0142y BigDecimal {0}
postgresql.res.badbyte:Z\u0142y Byte {0}
postgresql.res.baddate:Z\u0142y Date Format przy {0} w {1}
postgresql.res.baddouble:Z\u0142y Double {0}
postgresql.res.badfloat:Z\u0142y Float {0}
postgresql.res.badint:Z\u0142y Integer {0}
postgresql.res.badlong:Z\u0142y Long {0}
postgresql.res.badshort:Z\u0142y Short {0}
postgresql.res.badtime:Z\u0142y Time {0}
postgresql.res.badtimestamp:Z\u0142y Timestamp Format przy {0} w {1}
postgresql.res.closed:ResultSet jest zamkni\u0119ty. Operacja niedozwolona.
postgresql.res.colname:Nieznana nazwa kolumny {0}.
postgresql.res.colrange:Indeks kolumny jest poza zakresem.
postgresql.res.nextrequired:Z\u0142a pozycja w ResultSet, mo\u017ce musi\u0107 wywo\u0142a\u0107 next().
postgresql.serial.interface:Nie mo\u017cna serializowa\u0107 interfejsu.
postgresql.serial.namelength:D\u0142ugo\u015b\u0107 nazwy klasy i pakietu nie mog\u0105 by\u0107 d\u0142u\u017csze ni\u017c 64 znaki. {0} to {1} znak\u00f3w.
postgresql.serial.noclass:Nie znaleziono klasy dla typu {0}
postgresql.serial.table:W bazie nie ma tabelu dla typu {0}. Skontaktuj si\u0119 z administratorem, poniewa\u017c baza utraci\u0142a sp\u00f3jno\u015b\u0107.
postgresql.serial.underscore:Nazwy klas nie moga zawiera\u0107 _. Wprowadzi\u0142e\u015b {0}.
postgresql.stat.batch.error:Zadanie wsadowe {0} {1} zosta\u0142o przerwane. Wywo\u0142aj getNextException(), aby pozna\u0107 przyczyn\u0119.
postgresql.stat.noresult:Zapytanie nie zwr\u00f3ci\u0142o \u017cadnych wynik\u00f3w.
postgresql.stat.result:Zwr\u00f3cono wynik zapytania, cho\u0107 nie by\u0142 on oczekiwany.
postgresql.stream.eof:Serwer zerwa\u0142 po\u0142\u0105czenie. By\u0107 mo\u017ce akcja kt\u00f3r\u0105 podj\u0105\u0142e\u015b spowodowa\u0142a, \u017ce serwer zako\u0144czy\u0142 prac\u0119.
postgresql.stream.flush:Wyst\u0105pi\u0142 b\u0142\u0105d I/O podczas opr\u00f3\u017cniania bufora wyj\u015bciowego - {0}
postgresql.stream.ioerror:Wyst\u0105pi\u0142 b\u0142\u0105d I/O podczas odczytu z serwera - {0}
postgresql.stream.toomuch:Otrzymano zbyt wiele danych.
postgresql.unusual:Co\u015b niezwyk\u0142ego spowodowa\u0142o pad sterownika. Prosz\u0119, zg\u0142o\u015b ten wyj\u0105tek: {0}
postgresql.unimplemented:Ta metoda nie jest jeszcze obs\u0142ugiwana.
postgresql.unexpected:Zapytanie zwr\u00f3ci\u0142o nieoczekiwany wynik.
postgresql.updateable.notupdateable:ResultSet nie jest modyfikowalny (not updateable). Zapytanie, kt\u00f3re zwr\u00f3ci\u0142o ten wynik musi dotyczy\u0107 tylko jednej tabeli oraz musi pobiera\u0107 wszystkie klucze g\u0142\u00f3wne tej tabeli. Zobacz Specyfikacj\u0119 JDBC 2.1 API, rozdzia\u0142 5.6, aby uzyska\u0107 wi\u0119cej szczeg\u00f3\u0142\u00f3w.
postgresql.updateable.oninsertrow:Nie mo\u017cna wywo\u0142a\u0107 deleteRow() na wstawianym rekordzie.
postgresql.updateable.emptydelete:Nie mo\u017cna wywo\u0142a\u0107 deleteRow() na pustym wyniku.
postgresql.updateable.beforestartdelete:Przed pocz\u0105tkiek ResultSet. Nie mo\u017cna wywo\u0142a\u0107 deleteRow().
postgresql.updateable.afterlastdelete:Za ko\u0144cem ResultSet. Nie mo\u017cna wywo\u0142a\u0107 deleteRow().
postgresql.updateable.notoninsertrow:Nie na wstawianym rekordzie.
postgresql.updateable.inputstream:Input Stream jest null.
postgresql.updateable.ioerror:B\u0142\u0105d Input Stream - {0}
postgresql.call.noreturntype:Funkcja CallableStatement zosta\u0142a zadeklarowana, ale nie wywo\u0142ano 'registerOutParameter (1, <jaki\u015b typ>)'.
postgresql.call.noinout:PostgreSQL only supports function return value [@ 1] (no OUT or INOUT arguments)
postgresql.call.procasfunc:This Statement [{0}] defines a procedure call (needs ?= call <stmt> to be considered a function.
postgresql.call.malformed:Malformed stmt [{0}] usage : {1}
postgresql.call.funcover:Cannot execute Query a call to setXXX (1, ..) was made where argument 1 is the return value of a function.
postgresql.call.wrongget:Parameter of type {0} was registered but call to get{1} (sqltype={2}) was made.
postgresql.call.noreturnval:A CallableStatement Function was executed with nothing returned.
postgresql.call.wrongrtntype:A CallableStatement Function was executed and the return was of type ({0}) however type={1} was registered.
postgresql.input.fetch.gt0:Rozmiar pobierania musi by\u0107 warto\u015bci\u0105 dodatni\u0105 lub 0.
postgresql.input.query.gt0:Timeout zapytania musi by\u0107 warto\u015bci\u0105 dodatni\u0105 lub 0.
postgresql.input.rows.gt0:Maksymalna liczba rekord\u00f3w musi by\u0107 warto\u015bci\u0105 dodatni\u0105 lub 0.
postgresql.format.baddate:Podana data: {0} nie pasuje do wymaganego formatu: {1}.
postgresql.format.badtime:Podany czas: {0} nie pasuje do wymaganego formatu: {1}.
postgresql.format.badtimestamp:Podany timestamp: {0} nie pasuje do wymaganego formatu: {1}.
postgresql.input.field.gt0:Maksymalny rozmiar pola musi by\u0107 warto\u015bci\u0105 dodatni\u0105 lub 0.

View File

@ -1,114 +0,0 @@
# Message translation file for PostgreSQL JDBC driver
# Euler Taveira de Oliveira <euler@ufgnet.ufg.br>, 2003.
#
postgresql.arr.range:O índice do vetor está fora do intervalo.
postgresql.drv.version:Um erro interno ocorreu. Por favor recompile o driver.
postgresql.con.auth:O tipo de autenticação {0} não é suportado. Verifique se você configurou o arquivo pg_hba.conf incluindo a subrede ou endereço IP do cliente, e se está utilizando o esquema de autenticação suportado pelo driver.
postgresql.con.authfail:Um erro ocorreu quando se recebia a resposta de autenticação.
postgresql.con.backend:Inicialização do Backend falhou: {0}
postgresql.con.call:Instruções executáveis não são suportadas no momento.
postgresql.con.invalidchar:Caracter inválido foi encontrado. Isso é mais comumente causado por dados armazenados que contêm caracteres que são inválidos para a codificação que foi criado o banco de dados. O exemplo mais comum disso é armazenar dados de 8 bits em um banco de dados SQL_ASCII.
postgresql.con.closed:Conexão está fechada. Operação não é permitida.
postgresql.con.creobj:Falhou ao criar objeto para {0} {1}
postgresql.con.failed:A tentativa de conexão falhou porque {0}
postgresql.con.failed.bad.encoding:A tentativa de conexão falhou ao receber a codificação do servidor
postgresql.con.failed.bad.autocommit:A tentativa de conexão falhou ao receber o status de autocommit
postgresql.con.fathom:Impossível entender contador de atualização {0}
postgresql.con.garbled:Dados truncados foram recebidos.
postgresql.con.ioerror:Um erro de IO ocorreu ao enviar para o backend - {0}
postgresql.con.kerb4:Autenticação Kerberos 4 não é suportada por este driver.
postgresql.con.kerb5:Autenticação Kerberos 5 não é suportada por este driver.
postgresql.con.misc:Um erro de conexão ocorreu: {0}
postgresql.con.multres:Não pode manipular múltiplos grupos de resultados.
postgresql.con.pass:A propriedade senha não foi informada. Ela é obrigatória.
postgresql.con.refused:Conexão negada. Certifique se o nome da máquina e a porta estão corretos e se o postmaster está aceitando conexões TCP/IP.
postgresql.con.scm:Autenticação por credenciais SCM não é suportada por este driver.
postgresql.con.setup:Erro de protocolo. Configuração da sessão falhou.
postgresql.con.sslfail:Um erro ocorreu quando se estabelecia uma conexão SSL.
postgresql.con.sslnotsupported:O servidor não suporta SSL
postgresql.con.strobj:O objeto não pôde ser armazenado. Certifique se algumas tabelas já foram criadas no banco de dados.
postgresql.con.strobjex:Falhou ao armazenar objeto - {0}
postgresql.con.toolong:A Instrução SQL é muito longa - {0}
postgresql.con.isolevel:Nível de isolamento de transação {0} não é suportado.
postgresql.con.tuple:Tupla recebida antes de MetaData.
postgresql.con.type:Tipo de Resposta Desconhecido {0}
postgresql.con.user:A propriedade usuário não foi informada. Ela é obrigatória.
postgresql.error.detail:Detalhe: {0}
postgresql.error.hint:Dica: {0}
postgresql.error.position:Posição: {0}
postgresql.error.where:Onde: {0}
postgresql.error.location:Localização: {0}
postgresql.fp.error:Chamada ao FastPath retornou {0}
postgresql.fp.expint:Chamada ao Fastpath {0} - Nenhum resultado foi retornado e nós esperávamos um inteiro.
postgresql.fp.protocol:Erro do protocolo FastPath: {0}
postgresql.fp.send:Falhou ao enviar chamada ao fastpath {0} {1}
postgresql.fp.unknown:A função do fastpath {0} é desconhecida.
postgresql.geo.box:Conversão para box falhou - {0}
postgresql.geo.circle:Conversão para circle falhou - {0}
postgresql.geo.line:Conversão para line falhou - {0}
postgresql.geo.lseg:Conversão para lseg falhou - {0}
postgresql.geo.path:Não pode dizer se caminho está aberto ou fechado.
postgresql.geo.point:Conversão para point falhou - {0}
postgresql.jvm.version:O arquivo postgresql.jar não contém as classes JDBC corretas para esta JVM. Tente recontruí-lo. Se falhar, tente forçar especificando a versão na linha de comando utilizando o argumento -Djava.version=1.1 ou -Djava.version=1.2\nExceção foi {0}
postgresql.lo.init:falhou ao inicializar API de Objetos Grandes
postgresql.metadata.unavailable:Metadata indisponível.
postgresql.money:conversão para money falhou - {0}
postgresql.noupdate:Esse ResultSet não é atualizável.
postgresql.notsensitive:Esse ResultSet não é sensitivo a atualizações em tempo real depois que a consulta foi executada.
postgresql.psqlnotimp:O backend atualmente não suporta esta característica.
postgresql.prep.is:InputStream como parâmetro não é suportado
postgresql.prep.param:Nenhum valor especificado para o parâmetro {0}
postgresql.prep.range:Índice do parâmetro fora do intervalo.
postgresql.prep.type:Valor de Tipos desconhecidos.
postgresql.res.badbigdec:BigDecimal inválido {0}
postgresql.res.badbyte:Byte inválido {0}
postgresql.res.baddate:Formato de Data inválido {1} {0}
postgresql.res.baddouble:Double inválido {0}
postgresql.res.badfloat:Float inválido {0}
postgresql.res.badint:Integer inválido {0}
postgresql.res.badlong:Long inválido {0}
postgresql.res.badshort:Short inválido {0}
postgresql.res.badtime:Time inválido {0}
postgresql.res.badtimestamp:Formato de Timestamp inválido {1} {0}
postgresql.res.closed:Conjunto de resultados está fechado. Operação não é permitida.
postgresql.res.colname:O nome da coluna {0} não foi encontrado.
postgresql.res.colrange:O índice da coluna está fora do intervalo.
postgresql.res.nextrequired:Conjunto de resultados não está posicionado corretamente, talvez você precise chamar next().
postgresql.serial.interface:Você não pode serializar uma interface.
postgresql.serial.namelength:Tamanho do nome da Classe e do Pacote não pode ser maior do que 64 caracteres. {0} tem {1} caracteres.
postgresql.serial.noclass:Nenhuma classe encontrada para {0}
postgresql.serial.table:A tabela para {0} não está no banco de dados. Entre em contato com o DBA, e pergunte se o banco de dados não está em um estado inconsistente.
postgresql.serial.underscore:Nomes das Classes não podem ter _. Você forneceu {0}.
postgresql.stat.batch.error:Entrada em lote {0} {1} foi abortada. Chame getNextException() para ver a causa.
postgresql.stat.noresult:Nenhum resultado foi retornado pela consulta.
postgresql.stat.result:Um resultado foi retornado quando nenhum era esperado.
postgresql.stream.eof:O backend fechou a conexão. Possivelemte uma ação que você executou tenha causado o fechamento.
postgresql.stream.flush:Um erro de I/O ocorreu ao liberar a saída - {0}
postgresql.stream.ioerror:Um erro de I/O ocorreu ao ler do backend - {0}
postgresql.stream.toomuch:Muitos dados foram recebidos.
postgresql.unusual:Alguma coisa anormal ocorreu para causar a falha do driver. Por favor reporte essa exceção: {0}
postgresql.unimplemented:Este método não foi implementado ainda.
postgresql.unexpected:Um resultado inesperado foi retornado pela consulta.
postgresql.updateable.notupdateable: Conjunto de Resultados não é atualizável. A consulta que gerou esse conjunto de resultados deve selecionar somente uma tabela, e deve selecionar todas as chaves primárias daquela tabela. Veja a especificação na API do JDBC 2.1, seção 5.6 para mais informação.
postgresql.updateable.oninsertrow:Não pode chamar deleteRow() quando estiver inserindo registro
postgresql.updateable.emptydelete:Não pode utilizar deleteRow() em um conjunto de resultados vazio
postgresql.updateable.beforestartdelete:Antes do início do conjunto de resultados. Não pode chamar deleteRow().
postgresql.updateable.afterlastdelete:Depois do fim do conjunto de resultados. Não pode chamar deleteRow().
postgresql.updateable.notoninsertrow:Não está inserindo um registro.
postgresql.updateable.inputstream:Fluxo de Entrada é nulo.
postgresql.updateable.ioerror:Erro de Fluxo de Entrada - {0}
postgresql.call.noreturntype:Uma Instrução Executável foi declarada mas nenhuma chamada a 'registerOutParameter (1, <algum_tipo>)' foi feita.
postgresql.call.noinout:PostgreSQL só suporta função que retorna valor [@ 1] (nenhum argumento OUT ou INOUT)
postgresql.call.procasfunc:Esta Instrução [{0}] define uma chamada a um procedimento (necessita ?= chamar <stmt> para ser considerado uma função.
postgresql.call.malformed:Instrução mal formada [{0}] uso : {1}
postgresql.call.funcover:Não pode executar Consulta porque uma chamada a setXXX (1, ..) foi feita onde argumento 1 é o valor retornado pela função.
postgresql.call.wrongget:Parâmetro do tipo {0} foi registrado mas uma chamada a get{1} (tiposql={2}) foi feita.
postgresql.call.noreturnval:Uma Função foi executado e nada foi retornado.
postgresql.call.wrongrtntype:Uma Função foi executada e o retorno foi do tipo ({0}) contudo tipo={1} foi registrado.
postgresql.input.fetch.gt0:Tamanho da busca deve ser um valor maior ou igual a 0.
postgresql.input.query.gt0:Tempo de espera da Consulta deve ser um valor maior ou igual a 0.
postgresql.input.rows.gt0:Número máximo de linhas deve ser um valor maior ou igual a 0.
postgresql.format.baddate:A data informada: {0} não combina com o formato requerido: {1}.
postgresql.format.badtime:A hora informada: {0} não combina com o formato requerido: {1}.
postgresql.format.badtimestamp:O timestamp informado {0} não combina com o formato requerido: {1}.
postgresql.input.field.gt0:O tamanho máximo do campo deve ser um valor maior ou igual a 0.

View File

@ -1,118 +0,0 @@
# errors_ru.properties
# Translation into Russian, (C) 2003 Serguei A. Mokhov, mokhov@cs.concordia.ca
#
# ChangeLog:
#
# - October 12, 2003 - ... Initial translation
#
postgresql.arr.range:Индекс массива вне диапазона.
postgresql.drv.version:Внутренняя ошибка. Пожалуйста перекомпилируйте драйвер.
postgresql.con.auth:Тип аутентификации {0} не поддерживается. Проверьте что вы сконфигурировали файл pg_hba.conf чтобы включить IP адреса клиентов или подсеть. Также удостовертесь что он использует схему аутентификации поддерживаемую драйвером.
postgresql.con.authfail:Ошибка при получении запроса на аутентификацию.
postgresql.con.backend:Запуск бэкенда не удался: {0}
postgresql.con.call:Callable Statements are not supported at this time.
postgresql.con.invalidchar:Invalid character data was found. This is most likely caused by stored data containing characters that are invalid for the character set the database was created in. The most common example of this is storing 8bit data in a SQL_ASCII database.
postgresql.con.closed:Connection is closed. Operation is not permitted.
postgresql.con.creobj:Не удалось создать объект для {0} {1}
postgresql.con.failed:The connection attempt failed because {0}
postgresql.con.failed.bad.encoding:The connection attempt failed trying to get the server encoding
postgresql.con.failed.bad.autocommit:The connection attempt failed trying to get the autocommit status
postgresql.con.fathom:Unable to fathom update count {0}
postgresql.con.garbled:Garbled data received.
postgresql.con.ioerror:An IO erro occured while sending to the backend - {0}
postgresql.con.kerb4:Kerberos 4 authentication is not supported by this driver.
postgresql.con.kerb5:Kerberos 5 authentication is not supported by this driver.
postgresql.con.misc:A connection error has occurred: {0}
postgresql.con.multres:Cannot handle multiple result groups.
postgresql.con.pass:The password property is missing. It is mandatory.
postgresql.con.refused:Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections.
postgresql.con.scm:SCM credentials authentication is not supported by this driver.
postgresql.con.setup:Protocol error. Session setup failed.
postgresql.con.sslfail:An error occured while getting setting up the SSL connection.
postgresql.con.sslnotsupported:The server does not support SSL
postgresql.con.strobj:The object could not be stored. Check that any tables required have already been created in the database.
postgresql.con.strobjex:Failed to store object - {0}
postgresql.con.toolong:The SQL Statement is too long - {0}
postgresql.con.isolevel:Transaction isolation level {0} is not supported.
postgresql.con.tuple:Tuple received before MetaData.
postgresql.con.type:Unknown Response Type {0}
postgresql.con.user:The user property is missing. It is mandatory.
postgresql.error.detail:Подробности: {0}
postgresql.error.hint:Подсказка: {0}
postgresql.error.position:Позиция: {0}
postgresql.error.where:Где: {0}
postgresql.error.location:Местонахождение: {0}
postgresql.fp.error:FastPath call returned {0}
postgresql.fp.expint:Fastpath call {0} - No result was returned and we expected an integer.
postgresql.fp.protocol:FastPath protocol error: {0}
postgresql.fp.send:Failed to send fastpath call {0} {1}
postgresql.fp.unknown:The fastpath function {0} is unknown.
postgresql.geo.box:Conversion of box failed - {0}
postgresql.geo.circle:Conversion of circle failed - {0}
postgresql.geo.line:Conversion of line failed - {0}
postgresql.geo.lseg:Conversion of lseg failed - {0}
postgresql.geo.path:Cannot tell if path is open or closed.
postgresql.geo.point:Conversion of point failed - {0}
postgresql.jvm.version:The postgresql.jar file does not contain the correct JDBC classes for this JVM. Try rebuilding. If that fails, try forcing the version supplying it to the command line using the argument -Djava.version=1.1 or -Djava.version=1.2\nException thrown was {0}
postgresql.lo.init:failed to initialise LargeObject API
postgresql.metadata.unavailable:Metadata unavailable.
postgresql.money:conversion of money failed - {0}
postgresql.noupdate:This ResultSet is not updateable.
postgresql.notsensitive:This ResultSet is not sensitive to realtime updates after the query has run.
postgresql.psqlnotimp:The backend currently does not support this feature.
postgresql.prep.is:InputStream as parameter not supported
postgresql.prep.param:No value specified for parameter {0}
postgresql.prep.range:Parameter index out of range.
postgresql.prep.type:Unknown Types value.
postgresql.res.badbigdec:Bad BigDecimal {0}
postgresql.res.badbyte:Плохой Byte {0}
postgresql.res.baddate:Bad Date Format at {0} in {1}
postgresql.res.baddouble:Плохой Double {0}
postgresql.res.badfloat:Плохой Float {0}
postgresql.res.badint:Плохой Integer {0}
postgresql.res.badlong:Плохой Long {0}
postgresql.res.badshort:Плохой Short {0}
postgresql.res.badtime:Bad Time {0}
postgresql.res.badtimestamp:Bad Timestamp Format at {0} in {1}
postgresql.res.closed:Result set is closed. Operation is not permitted.
postgresql.res.colname:The column name {0} not found.
postgresql.res.colrange:Индекс колонки вне диапазона.
postgresql.res.nextrequired:Result set not positioned properly, perhaps you need to call next().
postgresql.serial.interface:Нельзя сериализовать интерфейс.
postgresql.serial.namelength:Class & Package name length cannot be longer than 64 characters. {0} is {1} characters.
postgresql.serial.noclass:Класс не найден для {0}
postgresql.serial.table:The table for {0} is not in the database. Contact the DBA, as the database is in an inconsistent state.
postgresql.serial.underscore:Class names may not have _ in them. You supplied {0}.
postgresql.stat.batch.error:Batch entry {0} {1} was aborted. Call getNextException() to see the cause.
postgresql.stat.noresult:No results were returned by the query.
postgresql.stat.result:A result was returned when none was expected.
postgresql.stream.eof:The backend has broken the connection. Possibly the action you have attempted has caused it to close.
postgresql.stream.flush:An I/O error has occured while flushing the output - {0}
postgresql.stream.ioerror:An I/O error occured while reading from backend - {0}
postgresql.stream.toomuch:Too much data was received.
postgresql.unusual:Something unusual has occured to cause the driver to fail. Please report this exception: {0}
postgresql.unimplemented:This method is not yet implemented.
postgresql.unexpected:An unexpected result was returned by a query.
postgresql.updateable.notupdateable: Result Set not updateable. The query that generated this result set must select only one table, and must select all primary keys from that table. See the JDBC 2.1 API Specification, section 5.6 for more details.
postgresql.updateable.oninsertrow:Can not call deleteRow() when on insert row
postgresql.updateable.emptydelete:Can't deleteRow() on empty result set
postgresql.updateable.beforestartdelete:Before start of result set. Can not call deleteRow().
postgresql.updateable.afterlastdelete:After end of result set. Can not call deleteRow().
postgresql.updateable.notoninsertrow:Not on insert row.
postgresql.updateable.inputstream:Input Stream is null.
postgresql.updateable.ioerror:ошибка Input Stream - {0}
postgresql.call.noreturntype:A CallableStatement Function was declared but no call to 'registerOutParameter (1, <some_type>)' was made.
postgresql.call.noinout:PostgreSQL only supports function return value [@ 1] (no OUT or INOUT arguments)
postgresql.call.procasfunc:This Statement [{0}] defines a procedure call (needs ?= call <stmt> to be considered a function.
postgresql.call.malformed:Malformed stmt [{0}] usage : {1}
postgresql.call.funcover:Cannot execute Query a call to setXXX (1, ..) was made where argument 1 is the return value of a function.
postgresql.call.wrongget:Parameter of type {0} was registered but call to get{1} (sqltype={2}) was made.
postgresql.call.noreturnval:A CallableStatement Function was executed with nothing returned.
postgresql.call.wrongrtntype:A CallableStatement Function was executed and the return was of type ({0}) however type={1} was registered.
postgresql.input.fetch.gt0:Fetch size must be a value greater than or equal to 0.
postgresql.input.query.gt0:Query Timeout must be a value greater than or equal to 0.
postgresql.input.rows.gt0:Maximum number of rows must be a value greater than or equal to 0.
postgresql.format.baddate:The date given: {0} does not match the format required: {1}.
postgresql.format.badtime:The time given: {0} does not match the format required: {1}.
postgresql.format.badtimestamp:The timestamp given {0} does not match the format required: {1}.
postgresql.input.field.gt0:The maximum field size must be a value greater than or equal to 0.

View File

@ -1,112 +0,0 @@
# 2003-11-25 Zhenbang Wei <forth@zbwei.net>
postgresql.arr.range:\u9663\u5217\u7d22\u5f15\u8d85\u904e\u8a31\u53ef\u7bc4\u570d\u3002
postgresql.drv.version:\u767c\u751f\u5167\u90e8\u932f\u8aa4\uff0c\u8acb\u91cd\u65b0\u7de8\u8b6f\u9a45\u52d5\u7a0b\u5f0f\u3002
postgresql.con.auth:\u4e0d\u652f\u63f4{0}\u8a8d\u8b49\uff0c\u8acb\u78ba\u5b9a\u60a8\u5df2\u7d93\u5c07\u5ba2\u6236\u7aef\u7684IP\u4f4d\u5740\u6216\u7db2\u8def\u5340\u6bb5\u4ee5\u53ca\u9a45\u52d5\u7a0b\u5f0f\u6240\u652f\u63f4\u7684\u8a8d\u8b49\u985e\u578b\u52a0\u5165pg_hba.conf\u3002
postgresql.con.authfail:\u8b80\u53d6\u8a8d\u8b49\u8acb\u6c42\u6642\u767c\u751f\u932f\u8aa4\u3002
postgresql.con.backend:\u5f8c\u7aef\u555f\u52d5\u5931\u6557\uff1a{0}
postgresql.con.call:\u76ee\u524d\u4e0d\u652f\u63f4CallableStatement\u3002
postgresql.con.invalidchar:\u767c\u73fe\u4e0d\u5408\u6cd5\u7684\u5b57\u5143\uff0c\u53ef\u80fd\u7684\u539f\u56e0\u662f\u6b32\u5132\u5b58\u7684\u8cc7\u6599\u4e2d\u5305\u542b\u8cc7\u6599\u5eab\u7684\u5b57\u5143\u96c6\u4e0d\u652f\u63f4\u7684\u5b57\u78bc\uff0c\u5176\u4e2d\u6700\u5e38\u898b\u4f8b\u5b50\u7684\u5c31\u662f\u5c078\u4f4d\u5143\u8cc7\u6599\u5b58\u5165\u4f7f\u7528SQL_ASCII\u7684\u8cc7\u6599\u5eab\u3002
postgresql.con.closed:\u9023\u7dda\u5df2\u95dc\u9589\uff0c\u4e0d\u5141\u8a31\u64cd\u4f5c\u3002
postgresql.con.creobj:\u70ba{0} {1}\u5efa\u7acb\u7269\u4ef6\u5931\u6557
postgresql.con.failed:\u9023\u7dda\u5931\u6557\uff0c\u56e0\u70ba{0}
postgresql.con.failed.bad.encofing:\u9023\u7dda\u5931\u6557\uff0c\u7121\u6cd5\u53d6\u5f97\u4f3a\u670d\u5668\u4f7f\u7528\u7684\u7de8\u78bc
postgresql.con.failed.bad.autocommit:\u9023\u7dda\u5931\u6557\uff0c\u7121\u6cd5\u53d6\u5f97autocommit\u72c0\u614b
postgresql.con.fathom:\u7121\u6cd5\u53d6\u5f97\u66f4\u65b0\u7684\u8cc7\u6599\u7b46\u6578{0}
postgresql.con.garbled:\u6536\u5230\u7121\u6548\u7684\u8cc7\u6599\u3002
postgresql.con.ioerror:\u50b3\u9001\u8cc7\u6599\u81f3\u5f8c\u7aef\u6642\u767c\u751fIO\u932f\u8aa4 - {0}
postgresql.con.kerb4:\u9a45\u52d5\u7a0b\u5f0f\u4e0d\u652f\u63f4Kerberos 4\u8a8d\u8b49\u3002
postgresql.con.kerb5:\u9a45\u52d5\u7a0b\u5f0f\u4e0d\u652f\u63f4Kerberos 5\u8a8d\u8b49\u3002
postgresql.con.misc:\u767c\u751f\u9023\u7dda\u932f\u8aa4\uff1a{0}
postgresql.con.multres:\u7121\u6cd5\u8655\u7406\u591a\u91cd\u67e5\u8a62\u7d50\u679c\u3002
postgresql.con.pass:\u6c92\u6709password\u5c6c\u6027\uff0c\u9019\u9805\u5c6c\u6027\u662f\u5fc5\u9700\u7684\u3002
postgresql.con.refused:\u62d2\u7d55\u9023\u7dda\uff0c\u8acb\u6aa2\u67e5\u4e3b\u6a5f\u540d\u7a31\u548c\u57e0\u865f\uff0c\u4e26\u78ba\u5b9apostmaster\u555f\u52d5\u6642\u4f7f\u7528\u4e86-i\u53c3\u6578\u958b\u555fTCP/IP\u7db2\u8def\u529f\u80fd\u3002
postgresql.con.scm:\u9a45\u52d5\u7a0b\u5f0f\u4e0d\u652f\u63f4SCM\u8a8d\u8b49\u3002
postgresql.con.setup:\u901a\u8a0a\u5354\u5b9a\u932f\u8aa4\uff0cSession\u521d\u59cb\u5316\u5931\u6557\u3002
postgresql.con.sslfail:\u9032\u884cSSL\u9023\u7dda\u6642\u767c\u751f\u932f\u8aa4\u3002
postgresql.con.sslnotsupported:\u4f3a\u670d\u5668\u4e0d\u652f\u63f4SSL\u9023\u7dda\u3002
postgresql.con.strobj:\u7121\u6cd5\u5132\u5b58\u7269\u4ef6\uff0c\u8acb\u78ba\u5b9a\u5df2\u7d93\u5728\u8cc7\u6599\u5eab\u4e2d\u5efa\u7acb\u8981\u4f7f\u7528\u7684\u8cc7\u6599\u8868\u3002
postgresql.con.strobjex:\u5132\u5b58\u7269\u4ef6\u5931\u6557 - {0}
postgresql.con.toolong:SQL \u6558\u8ff0\u904e\u9577 - {0}
postgresql.con.isolevel:\u4e0d\u652f\u63f4\u4ea4\u6613\u9694\u7d55\u7b49\u7d1a{0}\u3002
postgresql.con.tuple:Tuple\u5728MetaData\u4e4b\u524d\u50b3\u56de\u3002
postgresql.con.type:\u4e0d\u660e\u7684\u56de\u61c9\u985e\u578b{0}
postgresql.con.user:\u6c92\u6709user\u5c6c\u6027\uff0c\u9019\u9805\u5c6c\u6027\u662f\u5fc5\u9700\u7684\u3002
postgresql.error.detail:Detail: {0}
postgresql.error.hint:Hint: {0}
postgresql.error.position:Position: {0}
postgresql.error.where:Where: {0}
postgresql.error.location:Location: {0}
postgresql.fp.error:FastPath\u547c\u53eb\u50b3\u56de{0}
postgresql.fp.expint:Fastpath\u547c\u53eb{0} - \u6c92\u6709\u50b3\u56de\u503c\uff0c\u61c9\u8a72\u50b3\u56de\u4e00\u500b\u6574\u6578\u3002
postgresql.fp.protocol:FastPath\u5354\u5b9a\u932f\u8aa4\uff1a{0}
postgresql.fp.send:\u50b3\u9001fastpath\u547c\u53eb{0} {1}\u5931\u6557
postgresql.fp.unknown:\u4e0d\u660e\u7684fastpath\u51fd\u5f0f{0}\u3002
postgresql.geo.box:\u8f49\u63dbbox\u5931\u6557 - {0}
postgresql.geo.circle:\u8f49\u63dbcircle\u5931\u6557 - {0}
postgresql.geo.line:\u8f49\u63dbline\u5931\u6557 - {0}
postgresql.geo.lseg:\u8f49\u63dblseg\u5931\u6557 - {0}
postgresql.geo.path:\u7121\u6cd5\u5f97\u77e5path\u662f\u95dc\u9589\u6216\u958b\u555f\u3002
postgresql.geo.point:\u8f49\u63dbpoint\u5931\u6557 - {0}
postgresql.jvm.version:\u5728postgresql.jar\u4e2d\u627e\u4e0d\u5230\u6b63\u78ba\u7684JDBC\u985e\u5225\u4f9bJVM\u4f7f\u7528\uff0c\u8acb\u91cd\u65b0\u7de8\u8b6f\uff0c\u5982\u679c\u4ecd\u7136\u767c\u751f\u932f\u8aa4\uff0c\u8acb\u5728\u57f7\u884c\u6642\u7528-Djava.version=1.1\u6216-Djava.version=1.2\u5f37\u5236\u6307\u5b9a\u7248\u672c\n\u7522\u751f\u7684\u4f8b\u5916\u662f{0}
postgresql.lo.init:\u521d\u59cb\u5316LargeObject API\u5931\u6557\u3002
postgresql.metadata.unavailable:\u7121\u6cd5\u53d6\u5f97Metadata\u3002
postgresql.money:\u8f49\u63dbmoney\u5931\u6557 - {0}\u3002
postgresql.noupdate:\u67e5\u8a62\u7d50\u679c\u4e0d\u53ef\u66f4\u65b0\u3002
postgresql.notsensitive:\u67e5\u8a62\u7d50\u679c\u4e0d\u80fd\u5373\u6642\u53cd\u6620\u8b8a\u52d5\u7684\u8cc7\u6599\u3002
postgresql.psqlnotimp:\u5f8c\u7aef\u76ee\u524d\u4e0d\u652f\u63f4\u9019\u9805\u529f\u80fd\u3002
postgresql.prep.is:\u4e0d\u652f\u63f4\u4ee5InputStream\u505a\u70ba\u53c3\u6578\u3002
postgresql.prep.param:\u672a\u8a2d\u5b9a\u53c3\u6578{0}\u7684\u5167\u5bb9\u3002
postgresql.prep.range:\u53c3\u6578\u7d22\u5f15\u8d85\u904e\u8a31\u53ef\u7bc4\u570d\u3002
postgresql.prep.type:\u4e0d\u660e\u7684\u578b\u5225\u3002
postgresql.res.badbigdec:\u932f\u8aa4\u7684BigDecimal {0}
postgresql.res.badbyte:\u932f\u8aa4\u7684Byte {0}
postgresql.res.baddate:\u932f\u8aa4\u7684Date\u683c\u5f0f {1} \u65bc {0}
postgresql.res.baddouble:\u932f\u8aa4\u7684Double {0}
postgresql.res.badfloat:\u932f\u8aa4\u7684Float {0}
postgresql.res.badint:\u932f\u8aa4\u7684Integer {0}
postgresql.res.badlong:\u932f\u8aa4\u7684Long {0}
postgresql.res.badshort:\u932f\u8aa4\u7684Short {0}
postgresql.res.badtime:\u932f\u8aa4\u7684Time {0}
postgresql.res.badtimestamp:\u932f\u8aa4\u7684Timestamp\u683c\u5f0f{1}\u65bc{0}
postgresql.res.closed:ResultSet\u5df2\u7d93\u95dc\u9589\uff0c\u4e0d\u5141\u8a31\u5176\u5b83\u64cd\u4f5c\u3002
postgresql.res.colname:\u627e\u4e0d\u5230\u6b04\u4f4d\u540d\u7a31{0}\u3002
postgresql.res.colrange:\u6b04\u4f4d\u7d22\u5f15\u8d85\u904e\u8a31\u53ef\u7bc4\u570d\u3002
postgresql.res.nextrequired:\u67e5\u8a62\u7d50\u679c\u6307\u6a19\u4f4d\u7f6e\u4e0d\u6b63\u78ba\uff0c\u60a8\u4e5f\u8a31\u9700\u8981\u547c\u53ebResultSet\u7684next()\u65b9\u6cd5\u3002
postgresql.serial.interface:\u4e0d\u5141\u8a31\u5c07\u4ecb\u9762\u5e8f\u5217\u5316\u3002
postgresql.serial.namelength:\u985e\u5225\u548c\u5305\u88dd\u7684\u540d\u7a31\uff0c\u9577\u5ea6\u4e0d\u80fd\u8d85\u904e32\u5b57\u5143\uff0c{0}\u7684\u9577\u5ea6\u662f{1}\u5b57\u5143\u3002
postgresql.serial.noclass:\u627e\u4e0d\u5230\u985e\u5225{0}\u3002
postgresql.serial.table:\u8655\u7406{0}\u6642\u627e\u4e0d\u5230\u8cc7\u6599\u8868\uff0c\u8cc7\u6599\u5eab\u72c0\u614b\u4e0d\u6b63\u5e38\uff0c\u8acb\u806f\u7d61DBA\u8655\u7406\u3002
postgresql.serial.underscore:\u985e\u5225\u540d\u7a31\u4e0d\u80fd\u4f7f\u7528_\u5b57\u5143\uff0c\u60a8\u6240\u7528\u7684\u540d\u7a31\u662f{0}\u3002
postgresql.stat.batch.error:\u6279\u6b21\u8655\u7406\u5ffd\u7565{0} {1}\u3002
postgresql.stat.noresult:\u6c92\u6709\u50b3\u56de\u4efb\u4f55\u67e5\u8a62\u7d50\u679c\u3002
postgresql.stat.result:\u50b3\u56de\u9810\u671f\u5916\u7684\u7d50\u679c\u3002
postgresql.stream.eof:\u5f8c\u7aef\u7d50\u675f\u9023\u7dda\uff0c\u4e5f\u8a31\u662f\u56e0\u70ba\u60a8\u6240\u57f7\u884c\u7684\u52d5\u4f5c\u5c0e\u81f4\u9023\u7dda\u4e2d\u65b7\u3002
postgresql.stream.flush:\u9001\u51fa\u8cc7\u6599\u6642\u767c\u751fI/O\u932f\u8aa4 - {0}
postgresql.stream.ioerror:\u5f9e\u5f8c\u7aef\u8b80\u53d6\u8cc7\u6599\u6642\u767c\u751fI/O\u932f\u8aa4 - {0}
postgresql.stream.toomuch:\u63a5\u6536\u904e\u591a\u8cc7\u6599\u3002
postgresql.unusual:\u4e0d\u660e\u7684\u539f\u56e0\u5c0e\u81f4\u9a45\u52d5\u7a0b\u5f0f\u767c\u751f\u932f\u8aa4\uff0c\u8acb\u56de\u5831\u9019\u500b\u4f8b\u5916\uff1a{0}
postgresql.unimplemented:\u9019\u500b\u65b9\u6cd5\u5c1a\u672a\u5be6\u4f5c\u3002
postgresql.unexpected:\u50b3\u56de\u975e\u9810\u671f\u7684\u67e5\u8a62\u7d50\u679c\u3002
postgresql.updateable.notupdateable:\u4e0d\u53ef\u66f4\u65b0\u7684ResultSet\u3002\u7528\u4f86\u7522\u751f\u9019\u500bResultSet\u7684SQL\u6307\u4ee4\u53ea\u80fd\u64cd\u4f5c\u4e00\u500b\u8cc7\u6599\u8868\uff0c\u4e26\u4e14\u5fc5\u9700\u9078\u64c7\u4e3b\u9375\u6b04\u4f4d\uff0c\u8acb\u53c3\u95b1JDBC 2.1 API\u898f\u683c\u66f85.6\u7bc0\u3002
postgresql.updateable.oninsertrow:\u6b63\u5728\u65b0\u589e\u4e00\u7b46\u8cc7\u6599\u6642\u4e0d\u884c\u547c\u53ebdeleteRow()\u65b9\u6cd5\u3002
postgresql.updateable.emptydelete:\u4e0d\u884c\u5728\u7a7a\u7684ResultSet\u4f7f\u7528deleteRow()\u65b9\u6cd5\u3002
postgresql.updateable.beforestartdelete:\u4e0d\u884c\u5728ResultSet\u7684\u7b2c\u4e00\u7b46\u8cc7\u6599\u4e4b\u524d\u547c\u53ebdeleteRow()\u65b9\u6cd5\u3002
postgresql.updateable.afterlastdelete:\u4e0d\u884c\u5728ResultSet\u7684\u6700\u5f8c\u4e00\u7b46\u8cc7\u6599\u4e4b\u5f8c\u547c\u53ebdeleteRow()\u65b9\u6cd5\u3002
postgresql.updateable.notoninsertrow:\u4e0d\u5728\u65b0\u589e\u7684\u8cc7\u6599\u5217\u4e0a\u3002
postgresql.updateable.inputstream:InputStream\u662fnull\u3002
postgresql.updateable.ioerror:InputStream\u932f\u8aa4\u3002
postgresql.call.noreturntype:\u5df2\u7d93\u5ba3\u544aCallableStatement\u51fd\u5f0f\uff0c\u4f46\u662f\u5c1a\u672a\u547c\u53eb'registerOutParameter (1, <some_type>)'\u3002
postgresql.call.noinout:PostgreSQL\u53ea\u652f\u63f4\u50b3\u56de\u503c\u70ba[@ 1]\u7684\u51fd\u5f0f(\u6c92\u6709OUT\u6216INPUT\u5f15\u6578)\u3002
postgresql.call.procasfunc:\u6558\u8ff0[{0}]\u5b9a\u7fa9\u4e86\u4e00\u500b\u9810\u5132\u7a0b\u5e8f(\u547c\u53eb\u51fd\u5f0f\u9700\u8981\u4f7f\u7528?= call <stmt>\u683c\u5f0f)\u3002
postgresql.call.malformed:\u932f\u8aa4\u7684\u6558\u8ff0[{0}]\u7528\u6cd5\uff1a{1}
postgresql.call.funcover:\u7121\u6cd5\u57f7\u884c\u67e5\u8a62\uff0c\u547c\u53eb\u4e86setXXX(1, ..)\uff0c\u4f46\u662f\u7b2c\u4e00\u500b\u5f15\u6578\u662f\u51fd\u5f0f\u7684\u50b3\u56de\u503c\u3002
postgresql.call.wrongget:\u5df2\u8a3b\u518a\u53c3\u6578\u578b\u5225{0}\uff0c\u4f46\u662f\u53c8\u547c\u53eb\u4e86get{1}(sqltype={2})\u3002
postgresql.call.noreturnval:CallableStatement\u57f7\u884c\u51fd\u5f0f\u5f8c\u6c92\u6709\u50b3\u56de\u503c\u3002
postgresql.call.wrongrtntype:CallableStatement\u57f7\u884c\u51fd\u5f0f\u5f8c\u50b3\u56de\u503c\u7684\u578b\u5225\u662f{0}\uff0c\u4f46\u662f\u8a3b\u518a\u7684\u578b\u5225\u662f{1}\u3002
postgresql.input.fetch.gt0:\u8cc7\u6599\u8b80\u53d6\u7b46\u6578(fetch size)\u5fc5\u9808\u5927\u65bc\u6216\u7b49\u65bc0\u3002
postgresql.input.query.gt0:\u67e5\u8a62\u903e\u6642\u7b49\u5019\u6642\u9593\u5fc5\u9808\u5927\u65bc\u6216\u7b49\u65bc0\u3002
postgresql.input.rows.gt0:\u6700\u5927\u8cc7\u6599\u8b80\u53d6\u7b46\u6578\u5fc5\u9808\u5927\u65bc\u6216\u7b49\u65bc0\u3002
postgresql.format.baddate:\u50b3\u5165\u7684\u65e5\u671f{0}\u8207\u8981\u6c42\u7684\u683c\u5f0f{1}\u4e0d\u7b26\u3002
postgresql.format.badtime:\u50b3\u5165\u7684\u6642\u9593{0}\u8207\u8981\u6c42\u7684\u683c\u5f0f{1}\u4e0d\u7b26\u3002
postgresql.format.badtimestamp:\u50b3\u5165\u7684\u6642\u9593\u6233\u8a18{0}\u8207\u8981\u6c42\u7684\u683c\u5f0f{1}\u4e0d\u7b26\u3002
postgresql.input.field.gt0:\u6700\u5927\u6b04\u4f4d\u5bb9\u91cf\u5fc5\u9808\u5927\u65bc\u6216\u7b49\u65bc0\u3002

View File

@ -1,430 +0,0 @@
/*-------------------------------------------------------------------------
*
* Fastpath.java
* This class implements the Fastpath api.
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/fastpath/Fastpath.java,v 1.20 2003/12/18 03:27:14 davec Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.fastpath;
import java.io.IOException;
import java.sql.SQLException;
import java.sql.ResultSet;
import java.util.Hashtable;
import org.postgresql.Driver;
import org.postgresql.core.BaseConnection;
import org.postgresql.core.PGStream;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
/*
* This class implements the Fastpath api.
*
* <p>This is a means of executing functions imbeded in the org.postgresql
* backend from within a java application.
*
* <p>It is based around the file src/interfaces/libpq/fe-exec.c
*
*/
public class Fastpath
{
// This maps the functions names to their id's (possible unique just
// to a connection).
protected Hashtable func = new Hashtable();
protected BaseConnection conn; // our connection
protected PGStream stream; // the network stream
/*
* Initialises the fastpath system
*
* @param conn BaseConnection to attach to
* @param stream The network stream to the backend
*/
public Fastpath(BaseConnection conn, PGStream stream)
{
this.conn = conn;
this.stream = stream;
}
/*
* Send a function call to the PostgreSQL backend
*
* @param fnid Function id
* @param resulttype True if the result is an integer, false for other results
* @param args FastpathArguments to pass to fastpath
* @return null if no data, Integer if an integer result, or byte[] otherwise
* @exception SQLException if a database-access error occurs.
*/
public Object fastpath(int fnid, boolean resulttype, FastpathArg[] args) throws SQLException
{
if (conn.getPGProtocolVersionMajor() == 3) {
return fastpathV3(fnid, resulttype, args);
} else {
return fastpathV2(fnid, resulttype, args);
}
}
private Object fastpathV3(int fnid, boolean resulttype, FastpathArg[] args) throws SQLException
{
// added Oct 7 1998 to give us thread safety
synchronized (stream)
{
// send the function call
try
{
int l_msgLen = 0;
l_msgLen += 16;
for (int i=0;i < args.length;i++)
l_msgLen += args[i].sendSize();
stream.SendChar('F');
stream.SendInteger(l_msgLen,4);
stream.SendInteger(fnid, 4);
stream.SendInteger(1,2);
stream.SendInteger(1,2);
stream.SendInteger(args.length,2);
for (int i = 0;i < args.length;i++)
args[i].send(stream);
stream.SendInteger(1,2);
// This is needed, otherwise data can be lost
stream.flush();
}
catch (IOException ioe)
{
throw new PSQLException("postgresql.fp.send", PSQLState.COMMUNICATION_ERROR, new Integer(fnid), ioe);
}
// Now handle the result
// Now loop, reading the results
Object result = null; // our result
PSQLException error = null;
int c;
boolean l_endQuery = false;
while (!l_endQuery)
{
c = stream.ReceiveChar();
switch (c)
{
case 'A': // Asynchronous Notify
int pid = stream.ReceiveInteger(4);
String msg = stream.ReceiveString(conn.getEncoding());
conn.addNotification(new org.postgresql.core.Notification(msg, pid));
break;
//------------------------------
// Error message returned
case 'E':
int l_elen = stream.ReceiveIntegerR(4);
String totalMessage = conn.getEncoding().decode(stream.Receive(l_elen-4));
PSQLException l_error = PSQLException.parseServerError(totalMessage);
if (error != null) {
error.setNextException(l_error);
} else {
error = l_error;
}
break;
//------------------------------
// Notice from backend
case 'N':
int l_nlen = stream.ReceiveIntegerR(4);
conn.addWarning(conn.getEncoding().decode(stream.Receive(l_nlen-4)));
break;
case 'V':
int l_msgLen = stream.ReceiveIntegerR(4);
int l_valueLen = stream.ReceiveIntegerR(4);
if (l_valueLen == -1)
{
//null value
}
else if (l_valueLen == 0)
{
result = new byte[0];
}
else
{
// Return an Integer if
if (resulttype)
result = new Integer(stream.ReceiveIntegerR(l_valueLen));
else
{
byte buf[] = new byte[l_valueLen];
stream.Receive(buf, 0, l_valueLen);
result = buf;
}
}
break;
case 'Z':
//TODO: use size better
if (stream.ReceiveIntegerR(4) != 5) throw new PSQLException("postgresql.con.setup", PSQLState.CONNECTION_UNABLE_TO_CONNECT);
//TODO: handle transaction status
char l_tStatus = (char)stream.ReceiveChar();
l_endQuery = true;
break;
default:
throw new PSQLException("postgresql.fp.protocol", PSQLState.COMMUNICATION_ERROR, new Character((char)c));
}
}
if ( error != null )
throw error;
return result;
}
}
private Object fastpathV2(int fnid, boolean resulttype, FastpathArg[] args) throws SQLException
{
// added Oct 7 1998 to give us thread safety
synchronized (stream)
{
// send the function call
try
{
// 70 is 'F' in ASCII. Note: don't use SendChar() here as it adds padding
// that confuses the backend. The 0 terminates the command line.
stream.SendInteger(70, 1);
stream.SendInteger(0, 1);
stream.SendInteger(fnid, 4);
stream.SendInteger(args.length, 4);
for (int i = 0;i < args.length;i++)
args[i].send(stream);
// This is needed, otherwise data can be lost
stream.flush();
}
catch (IOException ioe)
{
//Should be sending exception as second arg.
throw new PSQLException("postgresql.fp.send", PSQLState.COMMUNICATION_ERROR, new Integer(fnid), ioe);
}
// Now handle the result
// Now loop, reading the results
Object result = null; // our result
StringBuffer errorMessage = null;
int c;
boolean l_endQuery = false;
while (!l_endQuery)
{
c = stream.ReceiveChar();
switch (c)
{
case 'A': // Asynchronous Notify
//TODO: do something with this
int pid = stream.ReceiveInteger(4);
String msg = stream.ReceiveString(conn.getEncoding());
break;
//------------------------------
// Error message returned
case 'E':
if ( errorMessage == null )
errorMessage = new StringBuffer();
errorMessage.append(stream.ReceiveString(conn.getEncoding()));
break;
//------------------------------
// Notice from backend
case 'N':
conn.addWarning(stream.ReceiveString(conn.getEncoding()));
break;
case 'V':
int l_nextChar = stream.ReceiveChar();
if (l_nextChar == 'G')
{
int sz = stream.ReceiveIntegerR(4);
// Return an Integer if
if (resulttype)
result = new Integer(stream.ReceiveIntegerR(sz));
else
{
byte buf[] = new byte[sz];
stream.Receive(buf, 0, sz);
result = buf;
}
//There should be a trailing '0'
int l_endChar = stream.ReceiveChar();
}
else
{
//it must have been a '0', thus no results
}
break;
case 'Z':
l_endQuery = true;
break;
default:
throw new PSQLException("postgresql.fp.protocol", PSQLState.COMMUNICATION_ERROR, new Character((char)c));
}
}
if ( errorMessage != null )
throw new PSQLException("postgresql.fp.error", PSQLState.COMMUNICATION_ERROR, errorMessage.toString());
return result;
}
}
/*
* Send a function call to the PostgreSQL backend by name.
*
* Note: the mapping for the procedure name to function id needs to exist,
* usually to an earlier call to addfunction().
*
* This is the prefered method to call, as function id's can/may change
* between versions of the backend.
*
* For an example of how this works, refer to org.postgresql.largeobject.LargeObject
*
* @param name Function name
* @param resulttype True if the result is an integer, false for other
* results
* @param args FastpathArguments to pass to fastpath
* @return null if no data, Integer if an integer result, or byte[] otherwise
* @exception SQLException if name is unknown or if a database-access error
* occurs.
* @see org.postgresql.largeobject.LargeObject
*/
public Object fastpath(String name, boolean resulttype, FastpathArg[] args) throws SQLException
{
if (Driver.logDebug)
Driver.debug("Fastpath: calling " + name);
return fastpath(getID(name), resulttype, args);
}
/*
* This convenience method assumes that the return value is an Integer
* @param name Function name
* @param args Function arguments
* @return integer result
* @exception SQLException if a database-access error occurs or no result
*/
public int getInteger(String name, FastpathArg[] args) throws SQLException
{
Integer i = (Integer)fastpath(name, true, args);
if (i == null)
throw new PSQLException("postgresql.fp.expint", name);
return i.intValue();
}
/*
* This convenience method assumes that the return value is an Integer
* @param name Function name
* @param args Function arguments
* @return byte[] array containing result
* @exception SQLException if a database-access error occurs or no result
*/
public byte[] getData(String name, FastpathArg[] args) throws SQLException
{
return (byte[])fastpath(name, false, args);
}
/*
* This adds a function to our lookup table.
*
* <p>User code should use the addFunctions method, which is based upon a
* query, rather than hard coding the oid. The oid for a function is not
* guaranteed to remain static, even on different servers of the same
* version.
*
* @param name Function name
* @param fnid Function id
*/
public void addFunction(String name, int fnid)
{
func.put(name, new Integer(fnid));
}
/*
* This takes a ResultSet containing two columns. Column 1 contains the
* function name, Column 2 the oid.
*
* <p>It reads the entire ResultSet, loading the values into the function
* table.
*
* <p><b>REMEMBER</b> to close() the resultset after calling this!!
*
* <p><b><em>Implementation note about function name lookups:</em></b>
*
* <p>PostgreSQL stores the function id's and their corresponding names in
* the pg_proc table. To speed things up locally, instead of querying each
* function from that table when required, a Hashtable is used. Also, only
* the function's required are entered into this table, keeping connection
* times as fast as possible.
*
* <p>The org.postgresql.largeobject.LargeObject class performs a query upon it's startup,
* and passes the returned ResultSet to the addFunctions() method here.
*
* <p>Once this has been done, the LargeObject api refers to the functions by
* name.
*
* <p>Dont think that manually converting them to the oid's will work. Ok,
* they will for now, but they can change during development (there was some
* discussion about this for V7.0), so this is implemented to prevent any
* unwarranted headaches in the future.
*
* @param rs ResultSet
* @exception SQLException if a database-access error occurs.
* @see org.postgresql.largeobject.LargeObjectManager
*/
public void addFunctions(ResultSet rs) throws SQLException
{
while (rs.next())
{
func.put(rs.getString(1), new Integer(rs.getInt(2)));
}
}
/*
* This returns the function id associated by its name
*
* <p>If addFunction() or addFunctions() have not been called for this name,
* then an SQLException is thrown.
*
* @param name Function name to lookup
* @return Function ID for fastpath call
* @exception SQLException is function is unknown.
*/
public int getID(String name) throws SQLException
{
Integer id = (Integer)func.get(name);
// may be we could add a lookup to the database here, and store the result
// in our lookup table, throwing the exception if that fails.
// We must, however, ensure that if we do, any existing ResultSet is
// unaffected, otherwise we could break user code.
//
// so, until we know we can do this (needs testing, on the TODO list)
// for now, we throw the exception and do no lookups.
if (id == null)
throw new PSQLException("postgresql.fp.unknown", PSQLState.UNEXPECTED_ERROR, name);
return id.intValue();
}
}

View File

@ -1,116 +0,0 @@
/*-------------------------------------------------------------------------
*
* FastpathArg.java
* Each fastpath call requires an array of arguments, the number and type
* dependent on the function being called.
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/fastpath/FastpathArg.java,v 1.6 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.fastpath;
import java.io.IOException;
public class FastpathArg
{
/*
* Type of argument, true=integer, false=byte[]
*/
public boolean type;
/*
* Integer value if type=true
*/
public int value;
/*
* Byte value if type=false;
*/
public byte[] bytes;
/*
* Constructs an argument that consists of an integer value
* @param value int value to set
*/
public FastpathArg(int value)
{
type = true;
this.value = value;
}
/*
* Constructs an argument that consists of an array of bytes
* @param bytes array to store
*/
public FastpathArg(byte bytes[])
{
type = false;
this.bytes = bytes;
}
/*
* Constructs an argument that consists of part of a byte array
* @param buf source array
* @param off offset within array
* @param len length of data to include
*/
public FastpathArg(byte buf[], int off, int len)
{
type = false;
bytes = new byte[len];
System.arraycopy(buf, off, bytes, 0, len);
}
/*
* Constructs an argument that consists of a String.
* @param s String to store
*/
public FastpathArg(String s)
{
this(s.getBytes());
}
/*
* This sends this argument down the network stream.
*
* <p>The stream sent consists of the length.int4 then the contents.
*
* <p><b>Note:</b> This is called from Fastpath, and cannot be called from
* client code.
*
* @param s output stream
* @exception IOException if something failed on the network stream
*/
protected void send(org.postgresql.core.PGStream s) throws IOException
{
if (type)
{
// argument is an integer
s.SendInteger(4, 4); // size of an integer
s.SendInteger(value, 4); // integer value of argument
}
else
{
// argument is a byte array
s.SendInteger(bytes.length, 4); // size of array
s.Send(bytes);
}
}
protected int sendSize()
{
if (type)
{
return 8;
}
else
{
return 4+bytes.length;
}
}
}

View File

@ -1,119 +0,0 @@
/*-------------------------------------------------------------------------
*
* PGbox.java
* This represents the box datatype within org.postgresql.
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/geometric/PGbox.java,v 1.6 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.geometric;
import org.postgresql.util.PGobject;
import org.postgresql.util.PGtokenizer;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import java.io.Serializable;
import java.sql.SQLException;
public class PGbox extends PGobject implements Serializable, Cloneable
{
/*
* These are the two points.
*/
public PGpoint point[] = new PGpoint[2];
/*
* @param x1 first x coordinate
* @param y1 first y coordinate
* @param x2 second x coordinate
* @param y2 second y coordinate
*/
public PGbox(double x1, double y1, double x2, double y2)
{
this();
this.point[0] = new PGpoint(x1, y1);
this.point[1] = new PGpoint(x2, y2);
}
/*
* @param p1 first point
* @param p2 second point
*/
public PGbox(PGpoint p1, PGpoint p2)
{
this();
this.point[0] = p1;
this.point[1] = p2;
}
/*
* @param s Box definition in PostgreSQL syntax
* @exception SQLException if definition is invalid
*/
public PGbox(String s) throws SQLException
{
this();
setValue(s);
}
/*
* Required constructor
*/
public PGbox()
{
setType("box");
}
/*
* This method sets the value of this object. It should be overidden,
* but still called by subclasses.
*
* @param value a string representation of the value of the object
* @exception SQLException thrown if value is invalid for this type
*/
public void setValue(String value) throws SQLException
{
PGtokenizer t = new PGtokenizer(value, ',');
if (t.getSize() != 2)
throw new PSQLException("postgresql.geo.box", PSQLState.DATA_TYPE_MISMATCH, value);
point[0] = new PGpoint(t.getToken(0));
point[1] = new PGpoint(t.getToken(1));
}
/*
* @param obj Object to compare with
* @return true if the two boxes are identical
*/
public boolean equals(Object obj)
{
if (obj instanceof PGbox)
{
PGbox p = (PGbox)obj;
return (p.point[0].equals(point[0]) && p.point[1].equals(point[1])) ||
(p.point[0].equals(point[1]) && p.point[1].equals(point[0]));
}
return false;
}
/*
* This must be overidden to allow the object to be cloned
*/
public Object clone()
{
return new PGbox((PGpoint)point[0].clone(), (PGpoint)point[1].clone());
}
/*
* @return the PGbox in the syntax expected by org.postgresql
*/
public String getValue()
{
return point[0].toString() + "," + point[1].toString();
}
}

View File

@ -1,125 +0,0 @@
/*-------------------------------------------------------------------------
*
* PGcircle.java
* This represents org.postgresql's circle datatype, consisting of a point
* and a radius
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/geometric/PGcircle.java,v 1.7 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.geometric;
import org.postgresql.util.PGobject;
import org.postgresql.util.PGtokenizer;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import java.io.Serializable;
import java.sql.SQLException;
public class PGcircle extends PGobject implements Serializable, Cloneable
{
/*
* This is the centre point
*/
public PGpoint center;
/*
* This is the radius
*/
double radius;
/*
* @param x coordinate of centre
* @param y coordinate of centre
* @param r radius of circle
*/
public PGcircle(double x, double y, double r)
{
this(new PGpoint(x, y), r);
}
/*
* @param c PGpoint describing the circle's centre
* @param r radius of circle
*/
public PGcircle(PGpoint c, double r)
{
this();
this.center = c;
this.radius = r;
}
/*
* @param s definition of the circle in PostgreSQL's syntax.
* @exception SQLException on conversion failure
*/
public PGcircle(String s) throws SQLException
{
this();
setValue(s);
}
/*
* This constructor is used by the driver.
*/
public PGcircle()
{
setType("circle");
}
/*
* @param s definition of the circle in PostgreSQL's syntax.
* @exception SQLException on conversion failure
*/
public void setValue(String s) throws SQLException
{
PGtokenizer t = new PGtokenizer(PGtokenizer.removeAngle(s), ',');
if (t.getSize() != 2)
throw new PSQLException("postgresql.geo.circle", PSQLState.DATA_TYPE_MISMATCH, s);
try
{
center = new PGpoint(t.getToken(0));
radius = Double.valueOf(t.getToken(1)).doubleValue();
}
catch (NumberFormatException e)
{
throw new PSQLException("postgresql.geo.circle", PSQLState.DATA_TYPE_MISMATCH, e);
}
}
/*
* @param obj Object to compare with
* @return true if the two boxes are identical
*/
public boolean equals(Object obj)
{
if (obj instanceof PGcircle)
{
PGcircle p = (PGcircle)obj;
return p.center.equals(center) && p.radius == radius;
}
return false;
}
/*
* This must be overidden to allow the object to be cloned
*/
public Object clone()
{
return new PGcircle((PGpoint)center.clone(), radius);
}
/*
* @return the PGcircle in the syntax expected by org.postgresql
*/
public String getValue()
{
return "<" + center + "," + radius + ">";
}
}

View File

@ -1,118 +0,0 @@
/*-------------------------------------------------------------------------
*
* PGline.java
* This implements a line consisting of two points.
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/geometric/PGline.java,v 1.6 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.geometric;
import org.postgresql.util.PGobject;
import org.postgresql.util.PGtokenizer;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import java.io.Serializable;
import java.sql.SQLException;
/*
* Currently line is not yet implemented in the backend, but this class
* ensures that when it's done were ready for it.
*/
public class PGline extends PGobject implements Serializable, Cloneable
{
/*
* These are the two points.
*/
public PGpoint point[] = new PGpoint[2];
/*
* @param x1 coordinate for first point
* @param y1 coordinate for first point
* @param x2 coordinate for second point
* @param y2 coordinate for second point
*/
public PGline(double x1, double y1, double x2, double y2)
{
this(new PGpoint(x1, y1), new PGpoint(x2, y2));
}
/*
* @param p1 first point
* @param p2 second point
*/
public PGline(PGpoint p1, PGpoint p2)
{
this();
this.point[0] = p1;
this.point[1] = p2;
}
/*
* @param s definition of the circle in PostgreSQL's syntax.
* @exception SQLException on conversion failure
*/
public PGline(String s) throws SQLException
{
this();
setValue(s);
}
/*
* reuired by the driver
*/
public PGline()
{
setType("line");
}
/*
* @param s Definition of the line segment in PostgreSQL's syntax
* @exception SQLException on conversion failure
*/
public void setValue(String s) throws SQLException
{
PGtokenizer t = new PGtokenizer(PGtokenizer.removeBox(s), ',');
if (t.getSize() != 2)
throw new PSQLException("postgresql.geo.line", PSQLState.DATA_TYPE_MISMATCH, s);
point[0] = new PGpoint(t.getToken(0));
point[1] = new PGpoint(t.getToken(1));
}
/*
* @param obj Object to compare with
* @return true if the two boxes are identical
*/
public boolean equals(Object obj)
{
if (obj instanceof PGline)
{
PGline p = (PGline)obj;
return (p.point[0].equals(point[0]) && p.point[1].equals(point[1])) ||
(p.point[0].equals(point[1]) && p.point[1].equals(point[0]));
}
return false;
}
/*
* This must be overidden to allow the object to be cloned
*/
public Object clone()
{
return new PGline((PGpoint)point[0].clone(), (PGpoint)point[1].clone());
}
/*
* @return the PGline in the syntax expected by org.postgresql
*/
public String getValue()
{
return "[" + point[0] + "," + point[1] + "]";
}
}

View File

@ -1,114 +0,0 @@
/*-------------------------------------------------------------------------
*
* PGlseg.java
* This implements a lseg (line segment) consisting of two points
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/geometric/PGlseg.java,v 1.6 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.geometric;
import org.postgresql.util.PGobject;
import org.postgresql.util.PGtokenizer;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import java.io.Serializable;
import java.sql.SQLException;
public class PGlseg extends PGobject implements Serializable, Cloneable
{
/*
* These are the two points.
*/
public PGpoint point[] = new PGpoint[2];
/*
* @param x1 coordinate for first point
* @param y1 coordinate for first point
* @param x2 coordinate for second point
* @param y2 coordinate for second point
*/
public PGlseg(double x1, double y1, double x2, double y2)
{
this(new PGpoint(x1, y1), new PGpoint(x2, y2));
}
/*
* @param p1 first point
* @param p2 second point
*/
public PGlseg(PGpoint p1, PGpoint p2)
{
this();
this.point[0] = p1;
this.point[1] = p2;
}
/*
* @param s definition of the circle in PostgreSQL's syntax.
* @exception SQLException on conversion failure
*/
public PGlseg(String s) throws SQLException
{
this();
setValue(s);
}
/*
* reuired by the driver
*/
public PGlseg()
{
setType("lseg");
}
/*
* @param s Definition of the line segment in PostgreSQL's syntax
* @exception SQLException on conversion failure
*/
public void setValue(String s) throws SQLException
{
PGtokenizer t = new PGtokenizer(PGtokenizer.removeBox(s), ',');
if (t.getSize() != 2)
throw new PSQLException("postgresql.geo.lseg", PSQLState.DATA_TYPE_MISMATCH);
point[0] = new PGpoint(t.getToken(0));
point[1] = new PGpoint(t.getToken(1));
}
/*
* @param obj Object to compare with
* @return true if the two boxes are identical
*/
public boolean equals(Object obj)
{
if (obj instanceof PGlseg)
{
PGlseg p = (PGlseg)obj;
return (p.point[0].equals(point[0]) && p.point[1].equals(point[1])) ||
(p.point[0].equals(point[1]) && p.point[1].equals(point[0]));
}
return false;
}
/*
* This must be overidden to allow the object to be cloned
*/
public Object clone()
{
return new PGlseg((PGpoint)point[0].clone(), (PGpoint)point[1].clone());
}
/*
* @return the PGlseg in the syntax expected by org.postgresql
*/
public String getValue()
{
return "[" + point[0] + "," + point[1] + "]";
}
}

View File

@ -1,164 +0,0 @@
/*-------------------------------------------------------------------------
*
* PGpath.java
* This implements a path (a multiple segmented line, which may be closed)
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/geometric/PGpath.java,v 1.7 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.geometric;
import org.postgresql.util.PGobject;
import org.postgresql.util.PGtokenizer;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import java.io.Serializable;
import java.sql.SQLException;
public class PGpath extends PGobject implements Serializable, Cloneable
{
/*
* True if the path is open, false if closed
*/
public boolean open;
/*
* The points defining this path
*/
public PGpoint points[];
/*
* @param points the PGpoints that define the path
* @param open True if the path is open, false if closed
*/
public PGpath(PGpoint[] points, boolean open)
{
this();
this.points = points;
this.open = open;
}
/*
* Required by the driver
*/
public PGpath()
{
setType("path");
}
/*
* @param s definition of the circle in PostgreSQL's syntax.
* @exception SQLException on conversion failure
*/
public PGpath(String s) throws SQLException
{
this();
setValue(s);
}
/*
* @param s Definition of the path in PostgreSQL's syntax
* @exception SQLException on conversion failure
*/
public void setValue(String s) throws SQLException
{
// First test to see if were open
if (s.startsWith("[") && s.endsWith("]"))
{
open = true;
s = PGtokenizer.removeBox(s);
}
else if (s.startsWith("(") && s.endsWith(")"))
{
open = false;
s = PGtokenizer.removePara(s);
}
else
throw new PSQLException("postgresql.geo.path", PSQLState.DATA_TYPE_MISMATCH);
PGtokenizer t = new PGtokenizer(s, ',');
int npoints = t.getSize();
points = new PGpoint[npoints];
for (int p = 0;p < npoints;p++)
points[p] = new PGpoint(t.getToken(p));
}
/*
* @param obj Object to compare with
* @return true if the two boxes are identical
*/
public boolean equals(Object obj)
{
if (obj instanceof PGpath)
{
PGpath p = (PGpath)obj;
if (p.points.length != points.length)
return false;
if (p.open != open)
return false;
for (int i = 0;i < points.length;i++)
if (!points[i].equals(p.points[i]))
return false;
return true;
}
return false;
}
/*
* This must be overidden to allow the object to be cloned
*/
public Object clone()
{
PGpoint ary[] = new PGpoint[points.length];
for (int i = 0;i < points.length;i++)
ary[i] = (PGpoint)points[i].clone();
return new PGpath(ary, open);
}
/*
* This returns the polygon in the syntax expected by org.postgresql
*/
public String getValue()
{
StringBuffer b = new StringBuffer(open ? "[" : "(");
for (int p = 0;p < points.length;p++)
{
if (p > 0)
b.append(",");
b.append(points[p].toString());
}
b.append(open ? "]" : ")");
return b.toString();
}
public boolean isOpen()
{
return open;
}
public boolean isClosed()
{
return !open;
}
public void closePath()
{
open = false;
}
public void openPath()
{
open = true;
}
}

View File

@ -1,184 +0,0 @@
/*-------------------------------------------------------------------------
*
* PGline.java
* It maps to the point datatype in org.postgresql.
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/geometric/PGpoint.java,v 1.7 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.geometric;
import org.postgresql.util.PGobject;
import org.postgresql.util.PGtokenizer;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import java.awt.Point;
import java.io.Serializable;
import java.sql.SQLException;
/*
* This implements a version of java.awt.Point, except it uses double
* to represent the coordinates.
*/
public class PGpoint extends PGobject implements Serializable, Cloneable
{
/*
* The X coordinate of the point
*/
public double x;
/*
* The Y coordinate of the point
*/
public double y;
/*
* @param x coordinate
* @param y coordinate
*/
public PGpoint(double x, double y)
{
this();
this.x = x;
this.y = y;
}
/*
* This is called mainly from the other geometric types, when a
* point is imbeded within their definition.
*
* @param value Definition of this point in PostgreSQL's syntax
*/
public PGpoint(String value) throws SQLException
{
this();
setValue(value);
}
/*
* Required by the driver
*/
public PGpoint()
{
setType("point");
}
/*
* @param s Definition of this point in PostgreSQL's syntax
* @exception SQLException on conversion failure
*/
public void setValue(String s) throws SQLException
{
PGtokenizer t = new PGtokenizer(PGtokenizer.removePara(s), ',');
try
{
x = Double.valueOf(t.getToken(0)).doubleValue();
y = Double.valueOf(t.getToken(1)).doubleValue();
}
catch (NumberFormatException e)
{
throw new PSQLException("postgresql.geo.point", PSQLState.DATA_TYPE_MISMATCH, e.toString());
}
}
/*
* @param obj Object to compare with
* @return true if the two boxes are identical
*/
public boolean equals(Object obj)
{
if (obj instanceof PGpoint)
{
PGpoint p = (PGpoint)obj;
return x == p.x && y == p.y;
}
return false;
}
/*
* This must be overidden to allow the object to be cloned
*/
public Object clone()
{
return new PGpoint(x, y);
}
/*
* @return the PGpoint in the syntax expected by org.postgresql
*/
public String getValue()
{
return "(" + x + "," + y + ")";
}
/*
* Translate the point with the supplied amount.
* @param x integer amount to add on the x axis
* @param y integer amount to add on the y axis
*/
public void translate(int x, int y)
{
translate((double)x, (double)y);
}
/*
* Translate the point with the supplied amount.
* @param x double amount to add on the x axis
* @param y double amount to add on the y axis
*/
public void translate(double x, double y)
{
this.x += x;
this.y += y;
}
/*
* Moves the point to the supplied coordinates.
* @param x integer coordinate
* @param y integer coordinate
*/
public void move(int x, int y)
{
setLocation(x, y);
}
/*
* Moves the point to the supplied coordinates.
* @param x double coordinate
* @param y double coordinate
*/
public void move(double x, double y)
{
this.x = x;
this.y = y;
}
/*
* Moves the point to the supplied coordinates.
* refer to java.awt.Point for description of this
* @param x integer coordinate
* @param y integer coordinate
* @see java.awt.Point
*/
public void setLocation(int x, int y)
{
move((double)x, (double)y);
}
/*
* Moves the point to the supplied java.awt.Point
* refer to java.awt.Point for description of this
* @param p Point to move to
* @see java.awt.Point
*/
public void setLocation(Point p)
{
setLocation(p.x, p.y);
}
}

View File

@ -1,118 +0,0 @@
/*-------------------------------------------------------------------------
*
* PGline.java
* This implements the polygon datatype within PostgreSQL.
*
* Copyright (c) 2003, PostgreSQL Global Development Group
*
* IDENTIFICATION
* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/geometric/PGpolygon.java,v 1.6 2003/11/29 19:52:09 pgsql Exp $
*
*-------------------------------------------------------------------------
*/
package org.postgresql.geometric;
import org.postgresql.util.PGobject;
import org.postgresql.util.PGtokenizer;
import java.io.Serializable;
import java.sql.SQLException;
public class PGpolygon extends PGobject implements Serializable, Cloneable
{
/*
* The points defining the polygon
*/
public PGpoint points[];
/*
* Creates a polygon using an array of PGpoints
*
* @param points the points defining the polygon
*/
public PGpolygon(PGpoint[] points)
{
this();
this.points = points;
}
/*
* @param s definition of the circle in PostgreSQL's syntax.
* @exception SQLException on conversion failure
*/
public PGpolygon(String s) throws SQLException
{
this();
setValue(s);
}
/*
* Required by the driver
*/
public PGpolygon()
{
setType("polygon");
}
/*
* @param s Definition of the polygon in PostgreSQL's syntax
* @exception SQLException on conversion failure
*/
public void setValue(String s) throws SQLException
{
PGtokenizer t = new PGtokenizer(PGtokenizer.removePara(s), ',');
int npoints = t.getSize();
points = new PGpoint[npoints];
for (int p = 0;p < npoints;p++)
points[p] = new PGpoint(t.getToken(p));
}
/*
* @param obj Object to compare with
* @return true if the two boxes are identical
*/
public boolean equals(Object obj)
{
if (obj instanceof PGpolygon)
{
PGpolygon p = (PGpolygon)obj;
if (p.points.length != points.length)
return false;
for (int i = 0;i < points.length;i++)
if (!points[i].equals(p.points[i]))
return false;
return true;
}
return false;
}
/*
* This must be overidden to allow the object to be cloned
*/
public Object clone()
{
PGpoint ary[] = new PGpoint[points.length];
for (int i = 0;i < points.length;i++)
ary[i] = (PGpoint)points[i].clone();
return new PGpolygon(ary);
}
/*
* @return the PGpolygon in the syntax expected by org.postgresql
*/
public String getValue()
{
StringBuffer b = new StringBuffer();
b.append("(");
for (int p = 0;p < points.length;p++)
{
if (p > 0)
b.append(",");
b.append(points[p].toString());
}
b.append(")");
return b.toString();
}
}

View File

@ -1,462 +0,0 @@
package org.postgresql.jdbc1;
import org.postgresql.core.Field;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Vector;
public abstract class AbstractJdbc1ResultSetMetaData
{
protected Vector rows;
protected Field[] fields;
/*
* Initialise for a result with a tuple set and
* a field descriptor set
*
* @param rows the Vector of rows returned by the ResultSet
* @param fields the array of field descriptors
*/
public AbstractJdbc1ResultSetMetaData(Vector rows, Field[] fields)
{
this.rows = rows;
this.fields = fields;
}
/*
* Whats the number of columns in the ResultSet?
*
* @return the number
* @exception SQLException if a database access error occurs
*/
public int getColumnCount() throws SQLException
{
return fields.length;
}
/*
* Is the column automatically numbered (and thus read-only)
* I believe that PostgreSQL does not support this feature.
*
* @param column the first column is 1, the second is 2...
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean isAutoIncrement(int column) throws SQLException
{
return false;
}
/*
* Does a column's case matter? ASSUMPTION: Any field that is
* not obviously case insensitive is assumed to be case sensitive
*
* @param column the first column is 1, the second is 2...
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean isCaseSensitive(int column) throws SQLException
{
int sql_type = getField(column).getSQLType();
switch (sql_type)
{
case Types.SMALLINT:
case Types.INTEGER:
case Types.FLOAT:
case Types.REAL:
case Types.DOUBLE:
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
return false;
default:
return true;
}
}
/*
* Can the column be used in a WHERE clause? Basically for
* this, I split the functions into two types: recognised
* types (which are always useable), and OTHER types (which
* may or may not be useable). The OTHER types, for now, I
* will assume they are useable. We should really query the
* catalog to see if they are useable.
*
* @param column the first column is 1, the second is 2...
* @return true if they can be used in a WHERE clause
* @exception SQLException if a database access error occurs
*/
public boolean isSearchable(int column) throws SQLException
{
int sql_type = getField(column).getSQLType();
// This switch is pointless, I know - but it is a set-up
// for further expansion.
switch (sql_type)
{
case Types.OTHER:
return true;
default:
return true;
}
}
/*
* Is the column a cash value? 6.1 introduced the cash/money
* type, which haven't been incorporated as of 970414, so I
* just check the type name for both 'cash' and 'money'
*
* @param column the first column is 1, the second is 2...
* @return true if its a cash column
* @exception SQLException if a database access error occurs
*/
public boolean isCurrency(int column) throws SQLException
{
String type_name = getField(column).getPGType();
return type_name.equals("cash") || type_name.equals("money");
}
/*
* Indicates the nullability of values in the designated column.
*
* @param column the first column is 1, the second is 2...
* @return one of the columnNullable values
* @exception SQLException if a database access error occurs
*/
public int isNullable(int column) throws SQLException
{
/*
* TODO This needs a real implementation, taking into account columns
* defined with NOT NULL or PRIMARY KEY, CHECK constraints, views,
* functions etc.
*/
return java.sql.ResultSetMetaData.columnNullableUnknown;
}
/*
* Is the column a signed number? In PostgreSQL, all numbers
* are signed, so this is trivial. However, strings are not
* signed (duh!)
*
* @param column the first column is 1, the second is 2...
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean isSigned(int column) throws SQLException
{
int sql_type = getField(column).getSQLType();
switch (sql_type)
{
case Types.SMALLINT:
case Types.INTEGER:
case Types.FLOAT:
case Types.REAL:
case Types.DOUBLE:
return true;
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
return false; // I don't know about these?
default:
return false;
}
}
/*
* What is the column's normal maximum width in characters?
*
* @param column the first column is 1, the second is 2, etc.
* @return the maximum width
* @exception SQLException if a database access error occurs
*/
public int getColumnDisplaySize(int column) throws SQLException
{
Field f = getField(column);
String type_name = f.getPGType();
int typmod = f.getMod();
// I looked at other JDBC implementations and couldn't find a consistent
// interpretation of the "display size" for numeric values, so this is our's
// FIXME: currently, only types with a SQL92 or SQL3 pendant are implemented - jens@jens.de
// fixed length data types
if (type_name.equals( "int2" ))
return 6; // -32768 to +32768 (5 digits and a sign)
if (type_name.equals( "int4" )
|| type_name.equals( "oid" ))
return 11; // -2147483648 to +2147483647
if (type_name.equals( "int8" ))
return 20; // -9223372036854775808 to +9223372036854775807
if (type_name.equals( "money" ))
return 12; // MONEY = DECIMAL(9,2)
if (type_name.equals( "float4" ))
return 11; // i checked it out ans wasn't able to produce more than 11 digits
if (type_name.equals( "float8" ))
return 20; // dito, 20
if (type_name.equals( "char" ))
return 1;
if (type_name.equals( "bool" ))
return 1;
if (type_name.equals( "date" ))
return 14; // "01/01/4713 BC" - "31/12/32767 AD"
if (type_name.equals( "time" ))
return 8; // 00:00:00-23:59:59
if (type_name.equals( "timestamp" ))
return 22; // hhmmm ... the output looks like this: 1999-08-03 22:22:08+02
// variable length fields
typmod -= 4;
if (type_name.equals( "bpchar" )
|| type_name.equals( "varchar" ))
return typmod; // VARHDRSZ=sizeof(int32)=4
if (type_name.equals( "numeric" ))
return ( (typmod >> 16) & 0xffff )
+ 1 + ( typmod & 0xffff ); // DECIMAL(p,s) = (p digits).(s digits)
// if we don't know better
return f.getLength();
}
/*
* What is the suggested column title for use in printouts and
* displays? We suggest the ColumnName!
*
* @param column the first column is 1, the second is 2, etc.
* @return the column label
* @exception SQLException if a database access error occurs
*/
public String getColumnLabel(int column) throws SQLException
{
return getColumnName(column);
}
/*
* What's a column's name?
*
* @param column the first column is 1, the second is 2, etc.
* @return the column name
* @exception SQLException if a database access error occurs
*/
public String getColumnName(int column) throws SQLException
{
Field f = getField(column);
if (f != null)
return f.getName();
return "field" + column;
}
/*
* What is a column's table's schema? This relies on us knowing
* the table name....which I don't know how to do as yet. The
* JDBC specification allows us to return "" if this is not
* applicable.
*
* @param column the first column is 1, the second is 2...
* @return the Schema
* @exception SQLException if a database access error occurs
*/
public String getSchemaName(int column) throws SQLException
{
return "";
}
/*
* What is a column's number of decimal digits.
*
* @param column the first column is 1, the second is 2...
* @return the precision
* @exception SQLException if a database access error occurs
*/
public int getPrecision(int column) throws SQLException
{
int sql_type = getField(column).getSQLType();
switch (sql_type)
{
case Types.SMALLINT:
return 5;
case Types.INTEGER:
return 10;
case Types.REAL:
return 8;
case Types.FLOAT:
return 16;
case Types.DOUBLE:
return 16;
case Types.VARCHAR:
return 0;
case Types.NUMERIC:
Field f = getField(column);
if (f != null)
return ((0xFFFF0000)&f.getMod()) >> 16;
else
return 0;
default:
return 0;
}
}
/*
* What is a column's number of digits to the right of the
* decimal point?
*
* @param column the first column is 1, the second is 2...
* @return the scale
* @exception SQLException if a database access error occurs
*/
public int getScale(int column) throws SQLException
{
int sql_type = getField(column).getSQLType();
switch (sql_type)
{
case Types.SMALLINT:
return 0;
case Types.INTEGER:
return 0;
case Types.REAL:
return 8;
case Types.FLOAT:
return 16;
case Types.DOUBLE:
return 16;
case Types.VARCHAR:
return 0;
case Types.NUMERIC:
Field f = getField(column);
if (f != null)
return (((0x0000FFFF)&f.getMod()) - 4);
else
return 0;
default:
return 0;
}
}
/*
* Whats a column's table's name? How do I find this out? Both
* getSchemaName() and getCatalogName() rely on knowing the table
* Name, so we need this before we can work on them.
*
* @param column the first column is 1, the second is 2...
* @return column name, or "" if not applicable
* @exception SQLException if a database access error occurs
*/
public String getTableName(int column) throws SQLException
{
return "";
}
/*
* What's a column's table's catalog name? As with getSchemaName(),
* we can say that if getTableName() returns n/a, then we can too -
* otherwise, we need to work on it.
*
* @param column the first column is 1, the second is 2...
* @return catalog name, or "" if not applicable
* @exception SQLException if a database access error occurs
*/
public String getCatalogName(int column) throws SQLException
{
return "";
}
/*
* What is a column's SQL Type? (java.sql.Type int)
*
* @param column the first column is 1, the second is 2, etc.
* @return the java.sql.Type value
* @exception SQLException if a database access error occurs
* @see org.postgresql.Field#getSQLType
* @see java.sql.Types
*/
public int getColumnType(int column) throws SQLException
{
return getField(column).getSQLType();
}
/*
* Whats is the column's data source specific type name?
*
* @param column the first column is 1, the second is 2, etc.
* @return the type name
* @exception SQLException if a database access error occurs
*/
public String getColumnTypeName(int column) throws SQLException
{
return getField(column).getPGType();
}
/*
* Is the column definitely not writable? In reality, we would
* have to check the GRANT/REVOKE stuff for this to be effective,
* and I haven't really looked into that yet, so this will get
* re-visited.
*
* @param column the first column is 1, the second is 2, etc.
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean isReadOnly(int column) throws SQLException
{
return false;
}
/*
* Is it possible for a write on the column to succeed? Again, we
* would in reality have to check the GRANT/REVOKE stuff, which
* I haven't worked with as yet. However, if it isn't ReadOnly, then
* it is obviously writable.
*
* @param column the first column is 1, the second is 2, etc.
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean isWritable(int column) throws SQLException
{
return !isReadOnly(column);
}
/*
* Will a write on this column definately succeed? Hmmm...this
* is a bad one, since the two preceding functions have not been
* really defined. I cannot tell is the short answer. I thus
* return isWritable() just to give us an idea.
*
* @param column the first column is 1, the second is 2, etc..
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean isDefinitelyWritable(int column) throws SQLException
{
return false;
}
// ********************************************************
// END OF PUBLIC INTERFACE
// ********************************************************
/*
* For several routines in this package, we need to convert
* a columnIndex into a Field[] descriptor. Rather than do
* the same code several times, here it is.
*
* @param columnIndex the first column is 1, the second is 2...
* @return the Field description
* @exception SQLException if a database access error occurs
*/
private Field getField(int columnIndex) throws SQLException
{
if (columnIndex < 1 || columnIndex > fields.length)
throw new PSQLException("postgresql.res.colrange", PSQLState.INVALID_PARAMETER_VALUE);
return fields[columnIndex - 1];
}
}

View File

@ -1,28 +0,0 @@
package org.postgresql.jdbc1;
import java.sql.*;
import java.util.Vector;
import org.postgresql.PGRefCursorResultSet;
import org.postgresql.core.BaseResultSet;
import org.postgresql.core.Field;
public class Jdbc1CallableStatement extends AbstractJdbc1Statement implements java.sql.CallableStatement
{
public Jdbc1CallableStatement(Jdbc1Connection connection, String sql) throws SQLException
{
super(connection, sql);
}
public BaseResultSet createResultSet (Field[] fields, java.util.Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException
{
return new Jdbc1ResultSet(this, fields, tuples, status, updateCount, insertOID, binaryCursor);
}
public PGRefCursorResultSet createRefCursorResultSet (String cursorName) throws SQLException
{
return new Jdbc1RefCursorResultSet(this, cursorName);
}
}

View File

@ -1,41 +0,0 @@
package org.postgresql.jdbc1;
import java.util.Vector;
import java.sql.*;
import org.postgresql.core.Field;
import org.postgresql.util.PSQLException;
/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc1/Jdbc1Connection.java,v 1.8 2003/11/29 19:52:10 pgsql Exp $
* This class implements the java.sql.Connection interface for JDBC1.
* However most of the implementation is really done in
* org.postgresql.jdbc1.AbstractJdbc1Connection
*/
public class Jdbc1Connection extends org.postgresql.jdbc1.AbstractJdbc1Connection implements java.sql.Connection
{
public java.sql.Statement createStatement() throws SQLException
{
return new org.postgresql.jdbc1.Jdbc1Statement(this);
}
public java.sql.PreparedStatement prepareStatement(String sql) throws SQLException
{
return new org.postgresql.jdbc1.Jdbc1PreparedStatement(this, sql);
}
public java.sql.CallableStatement prepareCall(String sql) throws SQLException
{
return new org.postgresql.jdbc1.Jdbc1CallableStatement(this, sql);
}
public java.sql.DatabaseMetaData getMetaData() throws SQLException
{
if (metadata == null)
metadata = new org.postgresql.jdbc1.Jdbc1DatabaseMetaData(this);
return metadata;
}
}

View File

@ -1,16 +0,0 @@
package org.postgresql.jdbc1;
import java.sql.*;
import java.util.*;
import org.postgresql.core.Field;
import org.postgresql.util.PSQLException;
public class Jdbc1DatabaseMetaData extends AbstractJdbc1DatabaseMetaData implements java.sql.DatabaseMetaData
{
public Jdbc1DatabaseMetaData(Jdbc1Connection conn)
{
super(conn);
}
}

View File

@ -1,26 +0,0 @@
package org.postgresql.jdbc1;
import java.sql.*;
import org.postgresql.PGRefCursorResultSet;
import org.postgresql.core.BaseResultSet;
import org.postgresql.core.Field;
public class Jdbc1PreparedStatement extends AbstractJdbc1Statement implements PreparedStatement
{
public Jdbc1PreparedStatement(Jdbc1Connection connection, String sql) throws SQLException
{
super(connection, sql);
}
public BaseResultSet createResultSet (Field[] fields, java.util.Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException
{
return new Jdbc1ResultSet(this, fields, tuples, status, updateCount, insertOID, binaryCursor);
}
public PGRefCursorResultSet createRefCursorResultSet (String cursorName) throws SQLException
{
return new Jdbc1RefCursorResultSet(this, cursorName);
}
}

View File

@ -1,44 +0,0 @@
package org.postgresql.jdbc1;
import java.sql.SQLException;
import org.postgresql.core.QueryExecutor;
import org.postgresql.core.BaseStatement;
import org.postgresql.PGRefCursorResultSet;
/** A real result set based on a ref cursor.
*
* @author Nic Ferrier <nferrier@tapsellferrier.co.uk>
*/
public class Jdbc1RefCursorResultSet extends Jdbc1ResultSet
implements PGRefCursorResultSet
{
// The name of the cursor being used.
String refCursorHandle;
// Indicates when the result set has activaly bound to the cursor.
boolean isInitialized = false;
Jdbc1RefCursorResultSet(BaseStatement statement, String refCursorName)
{
super(statement, null, null, null, -1, 0L, false);
this.refCursorHandle = refCursorName;
}
public String getRefCursor ()
{
return refCursorHandle;
}
public boolean next () throws SQLException
{
if (isInitialized)
return super.next();
// Initialize this res set with the rows from the cursor.
String[] toExec = { "FETCH ALL IN \"" + refCursorHandle + "\";" };
QueryExecutor.execute(toExec, new String[0], this);
isInitialized = true;
return super.next();
}
}

View File

@ -1,28 +0,0 @@
package org.postgresql.jdbc1;
import java.sql.*;
import java.util.Vector;
import org.postgresql.core.BaseStatement;
import org.postgresql.core.Field;
/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc1/Jdbc1ResultSet.java,v 1.7 2003/11/29 19:52:10 pgsql Exp $
* This class implements the java.sql.ResultSet interface for JDBC1.
* However most of the implementation is really done in
* org.postgresql.jdbc1.AbstractJdbc1ResultSet
*/
public class Jdbc1ResultSet extends org.postgresql.jdbc1.AbstractJdbc1ResultSet implements java.sql.ResultSet
{
public Jdbc1ResultSet(BaseStatement statement, Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor)
{
super(statement, fields, tuples, status, updateCount, insertOID, binaryCursor);
}
public java.sql.ResultSetMetaData getMetaData() throws SQLException
{
return new Jdbc1ResultSetMetaData(rows, fields);
}
}

View File

@ -1,14 +0,0 @@
package org.postgresql.jdbc1;
import java.util.Vector;
import org.postgresql.core.Field;
public class Jdbc1ResultSetMetaData extends AbstractJdbc1ResultSetMetaData implements java.sql.ResultSetMetaData
{
public Jdbc1ResultSetMetaData(Vector rows, Field[] fields)
{
super(rows, fields);
}
}

View File

@ -1,32 +0,0 @@
package org.postgresql.jdbc1;
import java.sql.*;
import java.util.Vector;
import org.postgresql.PGRefCursorResultSet;
import org.postgresql.core.BaseResultSet;
import org.postgresql.core.Field;
/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc1/Jdbc1Statement.java,v 1.7 2003/11/29 19:52:10 pgsql Exp $
* This class implements the java.sql.Statement interface for JDBC1.
* However most of the implementation is really done in
* org.postgresql.jdbc1.AbstractJdbc1Statement
*/
public class Jdbc1Statement extends org.postgresql.jdbc1.AbstractJdbc1Statement implements java.sql.Statement
{
public Jdbc1Statement (Jdbc1Connection c)
{
super(c);
}
public BaseResultSet createResultSet (Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException
{
return new Jdbc1ResultSet(this, fields, tuples, status, updateCount, insertOID, binaryCursor);
}
public PGRefCursorResultSet createRefCursorResultSet (String cursorName) throws SQLException
{
return new Jdbc1RefCursorResultSet(this, cursorName);
}
}

View File

@ -1,54 +0,0 @@
package org.postgresql.jdbc2;
import org.postgresql.PGConnection;
import org.postgresql.largeobject.LargeObject;
import org.postgresql.largeobject.LargeObjectManager;
import java.io.InputStream;
import java.sql.Blob;
import java.sql.SQLException;
public abstract class AbstractJdbc2Blob
{
private int oid;
private LargeObject lo;
public AbstractJdbc2Blob(PGConnection conn, int oid) throws SQLException
{
this.oid = oid;
LargeObjectManager lom = conn.getLargeObjectAPI();
this.lo = lom.open(oid);
}
public long length() throws SQLException
{
return lo.size();
}
public InputStream getBinaryStream() throws SQLException
{
return lo.getInputStream();
}
public byte[] getBytes(long pos, int length) throws SQLException
{
lo.seek((int)pos, LargeObject.SEEK_SET);
return lo.read(length);
}
/*
* For now, this is not implemented.
*/
public long position(byte[] pattern, long start) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/*
* This should be simply passing the byte value of the pattern Blob
*/
public long position(Blob pattern, long start) throws SQLException
{
return position(pattern.getBytes(0, (int)pattern.length()), start);
}
}

View File

@ -1,62 +0,0 @@
package org.postgresql.jdbc2;
import org.postgresql.PGConnection;
import org.postgresql.largeobject.LargeObject;
import org.postgresql.largeobject.LargeObjectManager;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.sql.Clob;
import java.sql.SQLException;
public class AbstractJdbc2Clob
{
private int oid;
private LargeObject lo;
public AbstractJdbc2Clob(PGConnection conn, int oid) throws SQLException
{
this.oid = oid;
LargeObjectManager lom = conn.getLargeObjectAPI();
this.lo = lom.open(oid);
}
public long length() throws SQLException
{
return lo.size();
}
public InputStream getAsciiStream() throws SQLException
{
return lo.getInputStream();
}
public Reader getCharacterStream() throws SQLException
{
return new InputStreamReader(lo.getInputStream());
}
public String getSubString(long i, int j) throws SQLException
{
lo.seek((int)i - 1);
return new String(lo.read(j));
}
/*
* For now, this is not implemented.
*/
public long position(String pattern, long start) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/*
* This should be simply passing the byte value of the pattern Blob
*/
public long position(Clob pattern, long start) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
}

View File

@ -1,173 +0,0 @@
package org.postgresql.jdbc2;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.SQLData;
import java.sql.SQLException;
import java.sql.Types;
/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc2/AbstractJdbc2Connection.java,v 1.7 2003/11/29 19:52:10 pgsql Exp $
* This class defines methods of the jdbc2 specification. This class extends
* org.postgresql.jdbc1.AbstractJdbc1Connection which provides the jdbc1
* methods. The real Connection class (for jdbc2) is org.postgresql.jdbc2.Jdbc2Connection
*/
public abstract class AbstractJdbc2Connection extends org.postgresql.jdbc1.AbstractJdbc1Connection
{
/*
* The current type mappings
*/
protected java.util.Map typemap;
public java.sql.Statement createStatement() throws SQLException
{
// The spec says default of TYPE_FORWARD_ONLY but everyone is used to
// using TYPE_SCROLL_INSENSITIVE
return createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY);
}
public abstract java.sql.Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException;
public java.sql.PreparedStatement prepareStatement(String sql) throws SQLException
{
return prepareStatement(sql, java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY);
}
public abstract java.sql.PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException;
public java.sql.CallableStatement prepareCall(String sql) throws SQLException
{
return prepareCall(sql, java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE, java.sql.ResultSet.CONCUR_READ_ONLY);
}
public abstract java.sql.CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException;
public java.util.Map getTypeMap() throws SQLException
{
return typemap;
}
public void setTypeMap(java.util.Map map) throws SQLException
{
typemap = map;
}
/*
* This overides the standard internal getObject method so that we can
* check the jdbc2 type map first
*/
public Object getObject(String type, String value) throws SQLException
{
if (typemap != null)
{
SQLData d = (SQLData) typemap.get(type);
if (d != null)
{
// Handle the type (requires SQLInput & SQLOutput classes to be implemented)
throw org.postgresql.Driver.notImplemented();
}
}
// Default to the original method
return super.getObject(type, value);
}
//Because the get/setLogStream methods are deprecated in JDBC2
//we use the get/setLogWriter methods here for JDBC2 by overriding
//the base version of this method
protected void enableDriverManagerLogging()
{
if (DriverManager.getLogWriter() == null)
{
DriverManager.setLogWriter(new PrintWriter(System.out));
}
}
/*
* This implemetation uses the jdbc2Types array to support the jdbc2
* datatypes. Basically jdbc1 and jdbc2 are the same, except that
* jdbc2 adds the Array types.
*/
public int getSQLType(String pgTypeName)
{
int sqlType = Types.OTHER; // default value
for (int i = 0;i < jdbc2Types.length;i++)
{
if (pgTypeName.equals(jdbc2Types[i]))
{
sqlType = jdbc2Typei[i];
break;
}
}
return sqlType;
}
/*
* This table holds the org.postgresql names for the types supported.
* Any types that map to Types.OTHER (eg POINT) don't go into this table.
* They default automatically to Types.OTHER
*
* Note: This must be in the same order as below.
*
* Tip: keep these grouped together by the Types. value
*/
private static final String jdbc2Types[] = {
"int2",
"int4", "oid",
"int8",
"cash", "money",
"numeric",
"float4",
"float8",
"bpchar", "char", "char2", "char4", "char8", "char16",
"varchar", "text", "name", "filename",
"bytea",
"bool",
"bit",
"date",
"time",
"abstime", "timestamp", "timestamptz",
"_bool", "_char", "_int2", "_int4", "_text",
"_oid", "_varchar", "_int8", "_float4", "_float8",
"_abstime", "_date", "_time", "_timestamp", "_numeric",
"_bytea"
};
/*
* This table holds the JDBC type for each entry above.
*
* Note: This must be in the same order as above
*
* Tip: keep these grouped together by the Types. value
*/
private static final int jdbc2Typei[] = {
Types.SMALLINT,
Types.INTEGER, Types.INTEGER,
Types.BIGINT,
Types.DOUBLE, Types.DOUBLE,
Types.NUMERIC,
Types.REAL,
Types.DOUBLE,
Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.BINARY,
Types.BIT,
Types.BIT,
Types.DATE,
Types.TIME,
Types.TIMESTAMP, Types.TIMESTAMP, Types.TIMESTAMP,
Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY,
Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY,
Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY,
Types.ARRAY
};
}

View File

@ -1,144 +0,0 @@
package org.postgresql.jdbc2;
import java.sql.SQLException;
public abstract class AbstractJdbc2DatabaseMetaData extends org.postgresql.jdbc1.AbstractJdbc1DatabaseMetaData
{
public AbstractJdbc2DatabaseMetaData(AbstractJdbc2Connection conn)
{
super(conn);
}
// ** JDBC 2 Extensions **
/*
* Does the database support the given result set type?
*
* @param type - defined in java.sql.ResultSet
* @return true if so; false otherwise
* @exception SQLException - if a database access error occurs
*/
public boolean supportsResultSetType(int type) throws SQLException
{
// The only type we don't support
return type != java.sql.ResultSet.TYPE_SCROLL_SENSITIVE;
}
/*
* Does the database support the concurrency type in combination
* with the given result set type?
*
* @param type - defined in java.sql.ResultSet
* @param concurrency - type defined in java.sql.ResultSet
* @return true if so; false otherwise
* @exception SQLException - if a database access error occurs
*/
public boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException
{
// These combinations are not supported!
if (type == java.sql.ResultSet.TYPE_SCROLL_SENSITIVE)
return false;
// We do support Updateable ResultSets
if (concurrency == java.sql.ResultSet.CONCUR_UPDATABLE)
return true;
// Everything else we do
return true;
}
/* lots of unsupported stuff... */
public boolean ownUpdatesAreVisible(int type) throws SQLException
{
return true;
}
public boolean ownDeletesAreVisible(int type) throws SQLException
{
return true;
}
public boolean ownInsertsAreVisible(int type) throws SQLException
{
// indicates that
return true;
}
public boolean othersUpdatesAreVisible(int type) throws SQLException
{
return false;
}
public boolean othersDeletesAreVisible(int i) throws SQLException
{
return false;
}
public boolean othersInsertsAreVisible(int type) throws SQLException
{
return false;
}
public boolean updatesAreDetected(int type) throws SQLException
{
return false;
}
public boolean deletesAreDetected(int i) throws SQLException
{
return false;
}
public boolean insertsAreDetected(int type) throws SQLException
{
return false;
}
/*
* Indicates whether the driver supports batch updates.
*/
public boolean supportsBatchUpdates() throws SQLException
{
return true;
}
/*
* Return user defined types in a schema
*/
public java.sql.ResultSet getUDTs(String catalog,
String schemaPattern,
String typeNamePattern,
int[] types
) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/*
* Retrieves the connection that produced this metadata object.
*
* @return the connection that produced this metadata object
*/
public java.sql.Connection getConnection() throws SQLException
{
return (java.sql.Connection)connection;
}
/* I don't find these in the spec!?! */
public boolean rowChangesAreDetected(int type) throws SQLException
{
return false;
}
public boolean rowChangesAreVisible(int type) throws SQLException
{
return false;
}
}

View File

@ -1,553 +0,0 @@
package org.postgresql.jdbc2;
import org.postgresql.core.Field;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import java.sql.SQLException;
import java.sql.Types;
import java.util.Vector;
public abstract class AbstractJdbc2ResultSetMetaData extends org.postgresql.jdbc1.AbstractJdbc1ResultSetMetaData
{
/*
* Initialise for a result with a tuple set and
* a field descriptor set
*
* @param rows the Vector of rows returned by the ResultSet
* @param fields the array of field descriptors
*/
public AbstractJdbc2ResultSetMetaData(Vector rows, Field[] fields)
{
super(rows, fields);
}
/*
* Whats the number of columns in the ResultSet?
*
* @return the number
* @exception SQLException if a database access error occurs
*/
public int getColumnCount() throws SQLException
{
return fields.length;
}
/*
* Is the column automatically numbered (and thus read-only)
* I believe that PostgreSQL does not support this feature.
*
* @param column the first column is 1, the second is 2...
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean isAutoIncrement(int column) throws SQLException
{
return false;
}
/*
* Does a column's case matter? ASSUMPTION: Any field that is
* not obviously case insensitive is assumed to be case sensitive
*
* @param column the first column is 1, the second is 2...
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean isCaseSensitive(int column) throws SQLException
{
int sql_type = getField(column).getSQLType();
switch (sql_type)
{
case Types.SMALLINT:
case Types.INTEGER:
case Types.FLOAT:
case Types.REAL:
case Types.DOUBLE:
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
return false;
default:
return true;
}
}
/*
* Can the column be used in a WHERE clause? Basically for
* this, I split the functions into two types: recognised
* types (which are always useable), and OTHER types (which
* may or may not be useable). The OTHER types, for now, I
* will assume they are useable. We should really query the
* catalog to see if they are useable.
*
* @param column the first column is 1, the second is 2...
* @return true if they can be used in a WHERE clause
* @exception SQLException if a database access error occurs
*/
public boolean isSearchable(int column) throws SQLException
{
int sql_type = getField(column).getSQLType();
// This switch is pointless, I know - but it is a set-up
// for further expansion.
switch (sql_type)
{
case Types.OTHER:
return true;
default:
return true;
}
}
/*
* Is the column a cash value? 6.1 introduced the cash/money
* type, which haven't been incorporated as of 970414, so I
* just check the type name for both 'cash' and 'money'
*
* @param column the first column is 1, the second is 2...
* @return true if its a cash column
* @exception SQLException if a database access error occurs
*/
public boolean isCurrency(int column) throws SQLException
{
String type_name = getField(column).getPGType();
return type_name.equals("cash") || type_name.equals("money");
}
/*
* Indicates the nullability of values in the designated column.
*
* @param column the first column is 1, the second is 2...
* @return one of the columnNullable values
* @exception SQLException if a database access error occurs
*/
public int isNullable(int column) throws SQLException
{
/*
* TODO This needs a real implementation, taking into account columns
* defined with NOT NULL or PRIMARY KEY, CHECK constraints, views,
* functions etc.
*/
return java.sql.ResultSetMetaData.columnNullableUnknown;
}
/*
* Is the column a signed number? In PostgreSQL, all numbers
* are signed, so this is trivial. However, strings are not
* signed (duh!)
*
* @param column the first column is 1, the second is 2...
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean isSigned(int column) throws SQLException
{
int sql_type = getField(column).getSQLType();
switch (sql_type)
{
case Types.SMALLINT:
case Types.INTEGER:
case Types.FLOAT:
case Types.REAL:
case Types.DOUBLE:
return true;
case Types.DATE:
case Types.TIME:
case Types.TIMESTAMP:
return false; // I don't know about these?
default:
return false;
}
}
/*
* What is the column's normal maximum width in characters?
*
* @param column the first column is 1, the second is 2, etc.
* @return the maximum width
* @exception SQLException if a database access error occurs
*/
public int getColumnDisplaySize(int column) throws SQLException
{
Field f = getField(column);
String type_name = f.getPGType();
int typmod = f.getMod();
// I looked at other JDBC implementations and couldn't find a consistent
// interpretation of the "display size" for numeric values, so this is our's
// FIXME: currently, only types with a SQL92 or SQL3 pendant are implemented - jens@jens.de
// fixed length data types
if (type_name.equals( "int2" ))
return 6; // -32768 to +32768 (5 digits and a sign)
if (type_name.equals( "int4" )
|| type_name.equals( "oid" ))
return 11; // -2147483648 to +2147483647
if (type_name.equals( "int8" ))
return 20; // -9223372036854775808 to +9223372036854775807
if (type_name.equals( "money" ))
return 12; // MONEY = DECIMAL(9,2)
if (type_name.equals( "float4" ))
return 11; // i checked it out ans wasn't able to produce more than 11 digits
if (type_name.equals( "float8" ))
return 20; // dito, 20
if (type_name.equals( "char" ))
return 1;
if (type_name.equals( "bool" ))
return 1;
if (type_name.equals( "date" ))
return 14; // "01/01/4713 BC" - "31/12/32767 AD"
if (type_name.equals( "time" ))
return 8; // 00:00:00-23:59:59
if (type_name.equals( "timestamp" ))
return 22; // hhmmm ... the output looks like this: 1999-08-03 22:22:08+02
// variable length fields
typmod -= 4;
if (type_name.equals( "bpchar" )
|| type_name.equals( "varchar" ))
return typmod; // VARHDRSZ=sizeof(int32)=4
if (type_name.equals( "numeric" ))
return ( (typmod >> 16) & 0xffff )
+ 1 + ( typmod & 0xffff ); // DECIMAL(p,s) = (p digits).(s digits)
// if we don't know better
return f.getLength();
}
/*
* What is the suggested column title for use in printouts and
* displays? We suggest the ColumnName!
*
* @param column the first column is 1, the second is 2, etc.
* @return the column label
* @exception SQLException if a database access error occurs
*/
public String getColumnLabel(int column) throws SQLException
{
return getColumnName(column);
}
/*
* What's a column's name?
*
* @param column the first column is 1, the second is 2, etc.
* @return the column name
* @exception SQLException if a database access error occurs
*/
public String getColumnName(int column) throws SQLException
{
Field f = getField(column);
if (f != null)
return f.getName();
return "field" + column;
}
/*
* What is a column's table's schema? This relies on us knowing
* the table name....which I don't know how to do as yet. The
* JDBC specification allows us to return "" if this is not
* applicable.
*
* @param column the first column is 1, the second is 2...
* @return the Schema
* @exception SQLException if a database access error occurs
*/
public String getSchemaName(int column) throws SQLException
{
return "";
}
/*
* What is a column's number of decimal digits.
*
* @param column the first column is 1, the second is 2...
* @return the precision
* @exception SQLException if a database access error occurs
*/
public int getPrecision(int column) throws SQLException
{
int sql_type = getField(column).getSQLType();
switch (sql_type)
{
case Types.SMALLINT:
return 5;
case Types.INTEGER:
return 10;
case Types.REAL:
return 8;
case Types.FLOAT:
return 16;
case Types.DOUBLE:
return 16;
case Types.VARCHAR:
return 0;
case Types.NUMERIC:
Field f = getField(column);
if (f != null)
return ((0xFFFF0000)&f.getMod()) >> 16;
else
return 0;
default:
return 0;
}
}
/*
* What is a column's number of digits to the right of the
* decimal point?
*
* @param column the first column is 1, the second is 2...
* @return the scale
* @exception SQLException if a database access error occurs
*/
public int getScale(int column) throws SQLException
{
int sql_type = getField(column).getSQLType();
switch (sql_type)
{
case Types.SMALLINT:
return 0;
case Types.INTEGER:
return 0;
case Types.REAL:
return 8;
case Types.FLOAT:
return 16;
case Types.DOUBLE:
return 16;
case Types.VARCHAR:
return 0;
case Types.NUMERIC:
Field f = getField(column);
if (f != null)
return (((0x0000FFFF)&f.getMod()) - 4);
else
return 0;
default:
return 0;
}
}
/*
* Whats a column's table's name? How do I find this out? Both
* getSchemaName() and getCatalogName() rely on knowing the table
* Name, so we need this before we can work on them.
*
* @param column the first column is 1, the second is 2...
* @return column name, or "" if not applicable
* @exception SQLException if a database access error occurs
*/
public String getTableName(int column) throws SQLException
{
return "";
}
/*
* What's a column's table's catalog name? As with getSchemaName(),
* we can say that if getTableName() returns n/a, then we can too -
* otherwise, we need to work on it.
*
* @param column the first column is 1, the second is 2...
* @return catalog name, or "" if not applicable
* @exception SQLException if a database access error occurs
*/
public String getCatalogName(int column) throws SQLException
{
return "";
}
/*
* What is a column's SQL Type? (java.sql.Type int)
*
* @param column the first column is 1, the second is 2, etc.
* @return the java.sql.Type value
* @exception SQLException if a database access error occurs
* @see org.postgresql.Field#getSQLType
* @see java.sql.Types
*/
public int getColumnType(int column) throws SQLException
{
return getField(column).getSQLType();
}
/*
* Whats is the column's data source specific type name?
*
* @param column the first column is 1, the second is 2, etc.
* @return the type name
* @exception SQLException if a database access error occurs
*/
public String getColumnTypeName(int column) throws SQLException
{
return getField(column).getPGType();
}
/**
* Is the column definitely not writable? In reality, we would
* have to check the GRANT/REVOKE stuff for this to be effective,
* and I haven't really looked into that yet, so this will get
* re-visited.
*
* @param column the first column is 1, the second is 2, etc.
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean isReadOnly(int column) throws SQLException
{
return false;
}
/**
* Is it possible for a write on the column to succeed? Again, we
* would in reality have to check the GRANT/REVOKE stuff, which
* I haven't worked with as yet. However, if it isn't ReadOnly, then
* it is obviously writable.
*
* @param column the first column is 1, the second is 2, etc.
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean isWritable(int column) throws SQLException
{
return !isReadOnly(column);
}
/**
* Will a write on this column definately succeed? Hmmm...this
* is a bad one, since the two preceding functions have not been
* really defined. I cannot tell is the short answer. I thus
* return isWritable() just to give us an idea.
*
* @param column the first column is 1, the second is 2, etc..
* @return true if so
* @exception SQLException if a database access error occurs
*/
public boolean isDefinitelyWritable(int column) throws SQLException
{
return false;
}
// ********************************************************
// END OF PUBLIC INTERFACE
// ********************************************************
/**
* For several routines in this package, we need to convert
* a columnIndex into a Field[] descriptor. Rather than do
* the same code several times, here it is.
*
* @param columnIndex the first column is 1, the second is 2...
* @return the Field description
* @exception SQLException if a database access error occurs
*/
private Field getField(int columnIndex) throws SQLException
{
if (columnIndex < 1 || columnIndex > fields.length)
throw new PSQLException("postgresql.res.colrange", PSQLState.INVALID_PARAMETER_VALUE);
return fields[columnIndex - 1];
}
// ** JDBC 2 Extensions **
// This can hook into our PG_Object mechanism
/**
* Returns the fully-qualified name of the Java class whose instances
* are manufactured if the method <code>ResultSet.getObject</code>
* is called to retrieve a value from the column.
*
* <code>ResultSet.getObject</code> may return a subclass of the class
* returned by this method.
*
* @param column the first column is 1, the second is 2, ...
* @return the fully-qualified name of the class in the Java programming
* language that would be used by the method
* <code>ResultSet.getObject</code> to retrieve the value in the specified
* column. This is the class name used for custom mapping.
* @exception SQLException if a database access error occurs
*/
public String getColumnClassName(int column) throws SQLException
{
/*
The following data type mapping came from ../Field.java.
"int2",
"int4","oid",
"int8",
"cash","money",
"numeric",
"float4",
"float8",
"bpchar","char","char2","char4","char8","char16",
"varchar","text","name","filename",
"bool",
"date",
"time",
"abstime","timestamp"
Types.SMALLINT,
Types.INTEGER,Types.INTEGER,
Types.BIGINT,
Types.DOUBLE,Types.DOUBLE,
Types.NUMERIC,
Types.REAL,
Types.DOUBLE,
Types.CHAR,Types.CHAR,Types.CHAR,Types.CHAR,Types.CHAR,Types.CHAR,
Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,Types.VARCHAR,
Types.BIT,
Types.DATE,
Types.TIME,
Types.TIMESTAMP,Types.TIMESTAMP
*/
Field field = getField(column);
int sql_type = field.getSQLType();
switch (sql_type)
{
case Types.BIT:
return ("java.lang.Boolean");
case Types.SMALLINT:
return ("java.lang.Short");
case Types.INTEGER:
return ("java.lang.Integer");
case Types.BIGINT:
return ("java.lang.Long");
case Types.NUMERIC:
return ("java.math.BigDecimal");
case Types.REAL:
return ("java.lang.Float");
case Types.DOUBLE:
return ("java.lang.Double");
case Types.CHAR:
case Types.VARCHAR:
return ("java.lang.String");
case Types.DATE:
return ("java.sql.Date");
case Types.TIME:
return ("java.sql.Time");
case Types.TIMESTAMP:
return ("java.sql.Timestamp");
case Types.BINARY:
case Types.VARBINARY:
return ("[B");
case Types.ARRAY:
return ("java.sql.Array");
default:
String type = field.getPGType();
if ("unknown".equals(type))
{
return ("java.lang.String");
}
return ("java.lang.Object");
}
}
}

View File

@ -1,434 +0,0 @@
package org.postgresql.jdbc2;
import java.io.*;
import java.math.*;
import java.sql.*;
import java.util.Vector;
import org.postgresql.Driver;
import org.postgresql.largeobject.*;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc2/AbstractJdbc2Statement.java,v 1.18 2003/11/29 19:52:10 pgsql Exp $
* This class defines methods of the jdbc2 specification. This class extends
* org.postgresql.jdbc1.AbstractJdbc1Statement which provides the jdbc1
* methods. The real Statement class (for jdbc2) is org.postgresql.jdbc2.Jdbc2Statement
*/
public abstract class AbstractJdbc2Statement extends org.postgresql.jdbc1.AbstractJdbc1Statement
{
protected Vector batch = null;
protected int resultsettype; // the resultset type to return
protected int concurrency; // is it updateable or not?
public AbstractJdbc2Statement (AbstractJdbc2Connection c)
{
super(c);
resultsettype = ResultSet.TYPE_SCROLL_INSENSITIVE;
concurrency = ResultSet.CONCUR_READ_ONLY;
}
public AbstractJdbc2Statement(AbstractJdbc2Connection connection, String sql) throws SQLException
{
super(connection, sql);
}
/*
* Execute a SQL statement that may return multiple results. We
* don't have to worry about this since we do not support multiple
* ResultSets. You can use getResultSet or getUpdateCount to
* retrieve the result.
*
* @param sql any SQL statement
* @return true if the next result is a ResulSet, false if it is
* an update count or there are no more results
* @exception SQLException if a database access error occurs
*/
public boolean execute() throws SQLException
{
boolean l_return = super.execute();
//Now do the jdbc2 specific stuff
//required for ResultSet.getStatement() to work and updateable resultsets
result.setStatement(this);
return l_return;
}
// ** JDBC 2 Extensions **
public void addBatch(String p_sql) throws SQLException
{
if (batch == null)
batch = new Vector();
Object[] l_statement = new Object[] {new String[] {p_sql}, new Object[0], new String[0]};
batch.addElement(l_statement);
}
public void clearBatch() throws SQLException
{
batch = null;
}
public int[] executeBatch() throws SQLException
{
if (batch == null)
batch = new Vector();
int size = batch.size();
int[] result = new int[size];
int i = 0;
try
{
//copy current state of statement
String[] l_origSqlFragments = m_sqlFragments;
Object[] l_origBinds = m_binds;
String[] l_origBindTypes = m_bindTypes;
for (i = 0;i < size;i++) {
//set state from batch
Object[] l_statement = (Object[])batch.elementAt(i);
this.m_sqlFragments = (String[])l_statement[0];
this.m_binds = (Object[])l_statement[1];
this.m_bindTypes = (String[])l_statement[2];
result[i] = this.executeUpdate();
}
//restore state of statement
m_sqlFragments = l_origSqlFragments;
m_binds = l_origBinds;
m_bindTypes = l_origBindTypes;
}
catch (SQLException e)
{
int[] resultSucceeded = new int[i];
System.arraycopy(result, 0, resultSucceeded, 0, i);
PBatchUpdateException updex =
new PBatchUpdateException("postgresql.stat.batch.error",
new Integer(i), m_sqlFragments[0], resultSucceeded);
updex.setNextException(e);
throw updex;
}
finally
{
batch.removeAllElements();
}
return result;
}
public void cancel() throws SQLException
{
connection.cancelQuery();
}
public Connection getConnection() throws SQLException
{
return (Connection) connection;
}
public int getFetchDirection() throws SQLException
{
throw new PSQLException("postgresql.psqlnotimp", PSQLState.NOT_IMPLEMENTED);
}
public int getResultSetConcurrency() throws SQLException
{
return concurrency;
}
public int getResultSetType() throws SQLException
{
return resultsettype;
}
public void setFetchDirection(int direction) throws SQLException
{
// I don't think this should happen, since it's a hint it should just
// fail quietly.
// throw Driver.notImplemented();
}
public void setFetchSize(int rows) throws SQLException
{
if (rows<0) throw new PSQLException("postgresql.input.fetch.gt0");
super.fetchSize = rows;
}
public void setResultSetConcurrency(int value) throws SQLException
{
concurrency = value;
}
public void setResultSetType(int value) throws SQLException
{
resultsettype = value;
}
public void addBatch() throws SQLException
{
if (batch == null)
batch = new Vector();
//we need to create copies, otherwise the values can be changed
Object[] l_newSqlFragments = null;
if (m_sqlFragments != null) {
l_newSqlFragments = new String[m_sqlFragments.length];
System.arraycopy(m_sqlFragments,0,l_newSqlFragments,0,m_sqlFragments.length);
}
Object[] l_newBinds = new Object[m_binds.length];
System.arraycopy(m_binds,0,l_newBinds,0,m_binds.length);
String[] l_newBindTypes = new String[m_bindTypes.length];
System.arraycopy(m_bindTypes,0,l_newBindTypes,0,m_bindTypes.length);
Object[] l_statement = new Object[] {l_newSqlFragments, l_newBinds, l_newBindTypes};
batch.addElement(l_statement);
}
public ResultSetMetaData getMetaData() throws SQLException
{
ResultSet rs = getResultSet();
if (rs != null)
return rs.getMetaData();
// Does anyone really know what this method does?
return null;
}
public void setArray(int i, java.sql.Array x) throws SQLException
{
setString(i, x.toString());
}
public void setBlob(int i, Blob x) throws SQLException
{
InputStream l_inStream = x.getBinaryStream();
LargeObjectManager lom = connection.getLargeObjectAPI();
int oid = lom.create();
LargeObject lob = lom.open(oid);
OutputStream los = lob.getOutputStream();
byte[] buf = new byte[4096];
try
{
// could be buffered, but then the OutputStream returned by LargeObject
// is buffered internally anyhow, so there would be no performance
// boost gained, if anything it would be worse!
int bytesRemaining = (int)x.length();
int numRead = l_inStream.read(buf, 0, Math.min(buf.length, bytesRemaining));
while (numRead != -1 && bytesRemaining > 0)
{
bytesRemaining -= numRead;
if ( numRead == buf.length )
los.write(buf); // saves a buffer creation and copy in LargeObject since it's full
else
los.write(buf,0,numRead);
numRead = l_inStream.read(buf, 0, Math.min(buf.length, bytesRemaining));
}
}
catch (IOException se)
{
throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, se);
}
finally
{
try
{
los.close();
l_inStream.close();
}
catch( Exception e ) {}
}
setInt(i, oid);
}
public void setCharacterStream(int i, java.io.Reader x, int length) throws SQLException
{
if (connection.haveMinimumCompatibleVersion("7.2"))
{
//Version 7.2 supports CharacterStream for for the PG text types
//As the spec/javadoc for this method indicate this is to be used for
//large text values (i.e. LONGVARCHAR) PG doesn't have a separate
//long varchar datatype, but with toast all the text datatypes are capable of
//handling very large values. Thus the implementation ends up calling
//setString() since there is no current way to stream the value to the server
char[] l_chars = new char[length];
int l_charsRead;
try
{
l_charsRead = x.read(l_chars, 0, length);
}
catch (IOException l_ioe)
{
throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, l_ioe);
}
setString(i, new String(l_chars, 0, l_charsRead));
}
else
{
//Version 7.1 only supported streams for LargeObjects
//but the jdbc spec indicates that streams should be
//available for LONGVARCHAR instead
LargeObjectManager lom = connection.getLargeObjectAPI();
int oid = lom.create();
LargeObject lob = lom.open(oid);
OutputStream los = lob.getOutputStream();
try
{
// could be buffered, but then the OutputStream returned by LargeObject
// is buffered internally anyhow, so there would be no performance
// boost gained, if anything it would be worse!
int c = x.read();
int p = 0;
while (c > -1 && p < length)
{
los.write(c);
c = x.read();
p++;
}
los.close();
}
catch (IOException se)
{
throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, se);
}
// lob is closed by the stream so don't call lob.close()
setInt(i, oid);
}
}
public void setClob(int i, Clob x) throws SQLException
{
InputStream l_inStream = x.getAsciiStream();
int l_length = (int) x.length();
LargeObjectManager lom = connection.getLargeObjectAPI();
int oid = lom.create();
LargeObject lob = lom.open(oid);
OutputStream los = lob.getOutputStream();
try
{
// could be buffered, but then the OutputStream returned by LargeObject
// is buffered internally anyhow, so there would be no performance
// boost gained, if anything it would be worse!
int c = l_inStream.read();
int p = 0;
while (c > -1 && p < l_length)
{
los.write(c);
c = l_inStream.read();
p++;
}
los.close();
}
catch (IOException se)
{
throw new PSQLException("postgresql.unusual", PSQLState.UNEXPECTED_ERROR, se);
}
// lob is closed by the stream so don't call lob.close()
setInt(i, oid);
}
public void setNull(int i, int t, String s) throws SQLException
{
setNull(i, t);
}
public void setRef(int i, Ref x) throws SQLException
{
throw Driver.notImplemented();
}
public void setDate(int i, java.sql.Date d, java.util.Calendar cal) throws SQLException
{
if (cal == null)
setDate(i, d);
else
{
cal.setTime(d);
setDate(i, new java.sql.Date(cal.getTime().getTime()));
}
}
public void setTime(int i, Time t, java.util.Calendar cal) throws SQLException
{
if (cal == null)
setTime(i, t);
else
{
cal.setTime(t);
setTime(i, new java.sql.Time(cal.getTime().getTime()));
}
}
public void setTimestamp(int i, Timestamp t, java.util.Calendar cal) throws SQLException
{
if (cal == null)
setTimestamp(i, t);
else
{
cal.setTime(t);
setTimestamp(i, new java.sql.Timestamp(cal.getTime().getTime()));
}
}
// ** JDBC 2 Extensions for CallableStatement**
public java.sql.Array getArray(int i) throws SQLException
{
throw Driver.notImplemented();
}
public java.math.BigDecimal getBigDecimal(int parameterIndex) throws SQLException
{
checkIndex (parameterIndex, Types.NUMERIC, "BigDecimal");
return ((BigDecimal)callResult);
}
public Blob getBlob(int i) throws SQLException
{
throw Driver.notImplemented();
}
public Clob getClob(int i) throws SQLException
{
throw Driver.notImplemented();
}
public Object getObject(int i, java.util.Map map) throws SQLException
{
throw Driver.notImplemented();
}
public Ref getRef(int i) throws SQLException
{
throw Driver.notImplemented();
}
public java.sql.Date getDate(int i, java.util.Calendar cal) throws SQLException
{
throw Driver.notImplemented();
}
public Time getTime(int i, java.util.Calendar cal) throws SQLException
{
throw Driver.notImplemented();
}
public Timestamp getTimestamp(int i, java.util.Calendar cal) throws SQLException
{
throw Driver.notImplemented();
}
// no custom types allowed yet..
public void registerOutParameter(int parameterIndex, int sqlType, String typeName) throws SQLException
{
throw Driver.notImplemented();
}
//This is needed by AbstractJdbc2ResultSet to determine if the query is updateable or not
protected String[] getSqlFragments()
{
return m_sqlFragments;
}
}

View File

@ -1,364 +0,0 @@
package org.postgresql.jdbc2;
import org.postgresql.core.BaseConnection;
import org.postgresql.core.BaseResultSet;
import org.postgresql.core.BaseStatement;
import org.postgresql.core.Field;
import org.postgresql.util.PSQLException;
import org.postgresql.util.PSQLState;
import java.math.BigDecimal;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.Map;
import java.util.Vector;
/*
* Array is used collect one column of query result data.
*
* <p>Read a field of type Array into either a natively-typed
* Java array object or a ResultSet. Accessor methods provide
* the ability to capture array slices.
*
* <p>Other than the constructor all methods are direct implementations
* of those specified for java.sql.Array. Please refer to the javadoc
* for java.sql.Array for detailed descriptions of the functionality
* and parameters of the methods of this class.
*
* @see ResultSet#getArray
*/
public class Array implements java.sql.Array
{
private BaseConnection conn = null;
private Field field = null;
private BaseResultSet rs;
private int idx = 0;
private String rawString = null;
/*
* Create a new Array
*
* @param conn a database connection
* @param idx 1-based index of the query field to load into this Array
* @param field the Field descriptor for the field to load into this Array
* @param rs the ResultSet from which to get the data for this Array
*/
public Array(BaseConnection conn, int idx, Field field, BaseResultSet rs )
throws SQLException
{
this.conn = conn;
this.field = field;
this.rs = rs;
this.idx = idx;
this.rawString = rs.getFixedString(idx);
}
public Object getArray() throws SQLException
{
return getArray( 1, 0, null );
}
public Object getArray(long index, int count) throws SQLException
{
return getArray( index, count, null );
}
public Object getArray(Map map) throws SQLException
{
return getArray( 1, 0, map );
}
public Object getArray(long index, int count, Map map) throws SQLException
{
if ( map != null ) // For now maps aren't supported.
throw org.postgresql.Driver.notImplemented();
if (index < 1)
throw new PSQLException("postgresql.arr.range", PSQLState.DATA_ERROR);
Object retVal = null;
ArrayList array = new ArrayList();
/* Check if the String is also not an empty array
* otherwise there will be an exception thrown below
* in the ResultSet.toX with an empty string.
* -- Doug Fields <dfields-pg-jdbc@pexicom.com> Feb 20, 2002 */
if ( rawString != null && !rawString.equals("{}") )
{
char[] chars = rawString.toCharArray();
StringBuffer sbuf = new StringBuffer();
boolean foundOpen = false;
boolean insideString = false;
for ( int i = 0; i < chars.length; i++ )
{
if ( chars[i] == '\\' )
//escape character that we need to skip
i++;
else if (!insideString && chars[i] == '{' )
{
if ( foundOpen ) // Only supports 1-D arrays for now
throw org.postgresql.Driver.notImplemented();
foundOpen = true;
continue;
}
else if (chars[i] == '"')
{
insideString = !insideString;
continue;
}
else if (!insideString && (chars[i] == ',' || chars[i] == '}') ||
i == chars.length - 1)
{
if ( chars[i] != '"' && chars[i] != '}' && chars[i] != ',' )
sbuf.append(chars[i]);
array.add( sbuf.toString() );
sbuf = new StringBuffer();
continue;
}
sbuf.append( chars[i] );
}
}
String[] arrayContents = (String[]) array.toArray( new String[array.size()] );
if ( count == 0 )
count = arrayContents.length;
index--;
if ( index + count > arrayContents.length )
throw new PSQLException("postgresql.arr.range", PSQLState.DATA_ERROR);
int i = 0;
switch ( getBaseType() )
{
case Types.BIT:
retVal = new boolean[ count ];
for ( ; count > 0; count-- )
((boolean[])retVal)[i++] = AbstractJdbc2ResultSet.toBoolean( arrayContents[(int)index++] );
break;
case Types.SMALLINT:
case Types.INTEGER:
retVal = new int[ count ];
for ( ; count > 0; count-- )
((int[])retVal)[i++] = AbstractJdbc2ResultSet.toInt( arrayContents[(int)index++] );
break;
case Types.BIGINT:
retVal = new long[ count ];
for ( ; count > 0; count-- )
((long[])retVal)[i++] = AbstractJdbc2ResultSet.toLong( arrayContents[(int)index++] );
break;
case Types.NUMERIC:
retVal = new BigDecimal[ count ];
for ( ; count > 0; count-- )
((BigDecimal[])retVal)[i++] = AbstractJdbc2ResultSet.toBigDecimal( arrayContents[(int)index++], 0 );
break;
case Types.REAL:
retVal = new float[ count ];
for ( ; count > 0; count-- )
((float[])retVal)[i++] = AbstractJdbc2ResultSet.toFloat( arrayContents[(int)index++] );
break;
case Types.DOUBLE:
retVal = new double[ count ];
for ( ; count > 0; count-- )
((double[])retVal)[i++] = AbstractJdbc2ResultSet.toDouble( arrayContents[(int)index++] );
break;
case Types.CHAR:
case Types.VARCHAR:
retVal = new String[ count ];
for ( ; count > 0; count-- )
((String[])retVal)[i++] = arrayContents[(int)index++];
break;
case Types.DATE:
retVal = new java.sql.Date[ count ];
for ( ; count > 0; count-- )
((java.sql.Date[])retVal)[i++] = AbstractJdbc2ResultSet.toDate( arrayContents[(int)index++] );
break;
case Types.TIME:
retVal = new java.sql.Time[ count ];
for ( ; count > 0; count-- )
((java.sql.Time[])retVal)[i++] = AbstractJdbc2ResultSet.toTime( arrayContents[(int)index++], rs, getBaseTypeName() );
break;
case Types.TIMESTAMP:
retVal = new Timestamp[ count ];
for ( ; count > 0; count-- )
((java.sql.Timestamp[])retVal)[i++] = AbstractJdbc2ResultSet.toTimestamp( arrayContents[(int)index++], rs, getBaseTypeName() );
break;
// Other datatypes not currently supported. If you are really using other types ask
// yourself if an array of non-trivial data types is really good database design.
default:
throw org.postgresql.Driver.notImplemented();
}
return retVal;
}
public int getBaseType() throws SQLException
{
return conn.getSQLType(getBaseTypeName());
}
public String getBaseTypeName() throws SQLException
{
String fType = field.getPGType();
if ( fType.charAt(0) == '_' )
fType = fType.substring(1);
return fType;
}
public java.sql.ResultSet getResultSet() throws SQLException
{
return getResultSet( 1, 0, null );
}
public java.sql.ResultSet getResultSet(long index, int count) throws SQLException
{
return getResultSet( index, count, null );
}
public java.sql.ResultSet getResultSet(Map map) throws SQLException
{
return getResultSet( 1, 0, map );
}
public java.sql.ResultSet getResultSet(long index, int count, java.util.Map map) throws SQLException
{
Object array = getArray( index, count, map );
Vector rows = new Vector();
Field[] fields = new Field[2];
fields[0] = new Field(conn, "INDEX", conn.getPGType("int2"), 2);
switch ( getBaseType() )
{
case Types.BIT:
boolean[] booleanArray = (boolean[]) array;
fields[1] = new Field(conn, "VALUE", conn.getPGType("bool"), 1);
for ( int i = 0; i < booleanArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( (booleanArray[i] ? "YES" : "NO") ); // Value
rows.addElement(tuple);
}
case Types.SMALLINT:
fields[1] = new Field(conn, "VALUE", conn.getPGType("int2"), 2);
case Types.INTEGER:
int[] intArray = (int[]) array;
if ( fields[1] == null )
fields[1] = new Field(conn, "VALUE", conn.getPGType("int4"), 4);
for ( int i = 0; i < intArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( Integer.toString(intArray[i]) ); // Value
rows.addElement(tuple);
}
break;
case Types.BIGINT:
long[] longArray = (long[]) array;
fields[1] = new Field(conn, "VALUE", conn.getPGType("int8"), 8);
for ( int i = 0; i < longArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( Long.toString(longArray[i]) ); // Value
rows.addElement(tuple);
}
break;
case Types.NUMERIC:
BigDecimal[] bdArray = (BigDecimal[]) array;
fields[1] = new Field(conn, "VALUE", conn.getPGType("numeric"), -1);
for ( int i = 0; i < bdArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( bdArray[i].toString() ); // Value
rows.addElement(tuple);
}
break;
case Types.REAL:
float[] floatArray = (float[]) array;
fields[1] = new Field(conn, "VALUE", conn.getPGType("float4"), 4);
for ( int i = 0; i < floatArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( Float.toString(floatArray[i]) ); // Value
rows.addElement(tuple);
}
break;
case Types.DOUBLE:
double[] doubleArray = (double[]) array;
fields[1] = new Field(conn, "VALUE", conn.getPGType("float8"), 8);
for ( int i = 0; i < doubleArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( Double.toString(doubleArray[i]) ); // Value
rows.addElement(tuple);
}
break;
case Types.CHAR:
fields[1] = new Field(conn, "VALUE", conn.getPGType("char"), 1);
case Types.VARCHAR:
String[] strArray = (String[]) array;
if ( fields[1] == null )
fields[1] = new Field(conn, "VALUE", conn.getPGType("varchar"), -1);
for ( int i = 0; i < strArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( strArray[i] ); // Value
rows.addElement(tuple);
}
break;
case Types.DATE:
java.sql.Date[] dateArray = (java.sql.Date[]) array;
fields[1] = new Field(conn, "VALUE", conn.getPGType("date"), 4);
for ( int i = 0; i < dateArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( dateArray[i].toString() ); // Value
rows.addElement(tuple);
}
break;
case Types.TIME:
java.sql.Time[] timeArray = (java.sql.Time[]) array;
fields[1] = new Field(conn, "VALUE", conn.getPGType("time"), 8);
for ( int i = 0; i < timeArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( timeArray[i].toString() ); // Value
rows.addElement(tuple);
}
break;
case Types.TIMESTAMP:
java.sql.Timestamp[] timestampArray = (java.sql.Timestamp[]) array;
fields[1] = new Field(conn, "VALUE", conn.getPGType("timestamp"), 8);
for ( int i = 0; i < timestampArray.length; i++ )
{
byte[][] tuple = new byte[2][0];
tuple[0] = conn.getEncoding().encode( Integer.toString((int)index + i) ); // Index
tuple[1] = conn.getEncoding().encode( timestampArray[i].toString() ); // Value
rows.addElement(tuple);
}
break;
// Other datatypes not currently supported. If you are really using other types ask
// yourself if an array of non-trivial data types is really good database design.
default:
throw org.postgresql.Driver.notImplemented();
}
BaseStatement stat = (BaseStatement) conn.createStatement();
return (ResultSet) stat.createResultSet(fields, rows, "OK", 1, 0, false);
}
public String toString()
{
return rawString;
}
}

View File

@ -1,12 +0,0 @@
package org.postgresql.jdbc2;
public class Jdbc2Blob extends AbstractJdbc2Blob implements java.sql.Blob
{
public Jdbc2Blob(org.postgresql.PGConnection conn, int oid) throws java.sql.SQLException
{
super(conn, oid);
}
}

View File

@ -1,28 +0,0 @@
package org.postgresql.jdbc2;
import java.sql.*;
import java.util.Vector;
import org.postgresql.PGRefCursorResultSet;
import org.postgresql.core.BaseResultSet;
import org.postgresql.core.Field;
public class Jdbc2CallableStatement extends org.postgresql.jdbc2.AbstractJdbc2Statement implements java.sql.CallableStatement
{
public Jdbc2CallableStatement(Jdbc2Connection connection, String sql) throws SQLException
{
super(connection, sql);
}
public BaseResultSet createResultSet (Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException
{
return new Jdbc2ResultSet(this, fields, tuples, status, updateCount, insertOID, binaryCursor);
}
public PGRefCursorResultSet createRefCursorResultSet (String cursorName) throws SQLException
{
return new Jdbc2RefCursorResultSet(this, cursorName);
}
}

View File

@ -1,12 +0,0 @@
package org.postgresql.jdbc2;
public class Jdbc2Clob extends AbstractJdbc2Clob implements java.sql.Clob
{
public Jdbc2Clob(org.postgresql.PGConnection conn, int oid) throws java.sql.SQLException
{
super(conn, oid);
}
}

View File

@ -1,51 +0,0 @@
package org.postgresql.jdbc2;
import java.sql.*;
import java.util.Vector;
import java.util.Hashtable;
import org.postgresql.core.Field;
/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc2/Jdbc2Connection.java,v 1.8 2003/11/29 19:52:10 pgsql Exp $
* This class implements the java.sql.Connection interface for JDBC2.
* However most of the implementation is really done in
* org.postgresql.jdbc2.AbstractJdbc2Connection or one of it's parents
*/
public class Jdbc2Connection extends org.postgresql.jdbc2.AbstractJdbc2Connection implements java.sql.Connection
{
public java.sql.Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException
{
Jdbc2Statement s = new Jdbc2Statement(this);
s.setResultSetType(resultSetType);
s.setResultSetConcurrency(resultSetConcurrency);
return s;
}
public java.sql.PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{
Jdbc2PreparedStatement s = new Jdbc2PreparedStatement(this, sql);
s.setResultSetType(resultSetType);
s.setResultSetConcurrency(resultSetConcurrency);
return s;
}
public java.sql.CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{
Jdbc2CallableStatement s = new org.postgresql.jdbc2.Jdbc2CallableStatement(this, sql);
s.setResultSetType(resultSetType);
s.setResultSetConcurrency(resultSetConcurrency);
return s;
}
public java.sql.DatabaseMetaData getMetaData() throws SQLException
{
if (metadata == null)
metadata = new org.postgresql.jdbc2.Jdbc2DatabaseMetaData(this);
return metadata;
}
}

View File

@ -1,11 +0,0 @@
package org.postgresql.jdbc2;
public class Jdbc2DatabaseMetaData extends org.postgresql.jdbc2.AbstractJdbc2DatabaseMetaData implements java.sql.DatabaseMetaData
{
public Jdbc2DatabaseMetaData(Jdbc2Connection conn)
{
super(conn);
}
}

View File

@ -1,29 +0,0 @@
package org.postgresql.jdbc2;
import java.sql.*;
import java.util.Vector;
import org.postgresql.PGRefCursorResultSet;
import org.postgresql.core.BaseResultSet;
import org.postgresql.core.Field;
public class Jdbc2PreparedStatement extends org.postgresql.jdbc2.AbstractJdbc2Statement implements java.sql.PreparedStatement
{
public Jdbc2PreparedStatement(Jdbc2Connection connection, String sql) throws SQLException
{
super(connection, sql);
}
public BaseResultSet createResultSet (Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException
{
return new Jdbc2ResultSet(this, fields, tuples, status, updateCount, insertOID, binaryCursor);
}
public PGRefCursorResultSet createRefCursorResultSet (String cursorName) throws SQLException
{
return new Jdbc2RefCursorResultSet(this, cursorName);
}
}

View File

@ -1,43 +0,0 @@
package org.postgresql.jdbc2;
import org.postgresql.core.QueryExecutor;
import org.postgresql.core.BaseStatement;
import org.postgresql.PGRefCursorResultSet;
/** A real result set based on a ref cursor.
*
* @author Nic Ferrier <nferrier@tapsellferrier.co.uk>
*/
public class Jdbc2RefCursorResultSet extends Jdbc2ResultSet
implements PGRefCursorResultSet
{
String refCursorHandle;
// Indicates when the result set has activaly bound to the cursor.
boolean isInitialized = false;
Jdbc2RefCursorResultSet(BaseStatement statement, String refCursorName) throws java.sql.SQLException
{
super(statement, null, null, null, -1, 0L, false);
this.refCursorHandle = refCursorName;
}
public String getRefCursor ()
{
return refCursorHandle;
}
public boolean next () throws java.sql.SQLException
{
if (isInitialized)
return super.next();
// Initialize this res set with the rows from the cursor.
String[] toExec = { "FETCH ALL IN \"" + refCursorHandle + "\";" };
QueryExecutor.execute(toExec, new String[0], this);
isInitialized = true;
return super.next();
}
}

View File

@ -1,46 +0,0 @@
package org.postgresql.jdbc2;
import java.sql.*;
import java.util.Vector;
import org.postgresql.core.BaseStatement;
import org.postgresql.core.Field;
/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc2/Jdbc2ResultSet.java,v 1.9 2003/11/29 19:52:10 pgsql Exp $
* This class implements the java.sql.ResultSet interface for JDBC2.
* However most of the implementation is really done in
* org.postgresql.jdbc2.AbstractJdbc2ResultSet or one of it's parents
*/
public class Jdbc2ResultSet extends org.postgresql.jdbc2.AbstractJdbc2ResultSet implements java.sql.ResultSet
{
public Jdbc2ResultSet(BaseStatement statement, Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor)
{
super(statement, fields, tuples, status, updateCount, insertOID, binaryCursor);
}
public ResultSetMetaData getMetaData() throws SQLException
{
return new Jdbc2ResultSetMetaData(rows, fields);
}
public java.sql.Clob getClob(int i) throws SQLException
{
wasNullFlag = (this_row[i - 1] == null);
if (wasNullFlag)
return null;
return new org.postgresql.jdbc2.Jdbc2Clob(connection, getInt(i));
}
public java.sql.Blob getBlob(int i) throws SQLException
{
wasNullFlag = (this_row[i - 1] == null);
if (wasNullFlag)
return null;
return new org.postgresql.jdbc2.Jdbc2Blob(connection, getInt(i));
}
}

View File

@ -1,13 +0,0 @@
package org.postgresql.jdbc2;
import java.util.Vector;
import org.postgresql.core.Field;
public class Jdbc2ResultSetMetaData extends AbstractJdbc2ResultSetMetaData implements java.sql.ResultSetMetaData
{
public Jdbc2ResultSetMetaData(Vector rows, Field[] fields)
{
super(rows, fields);
}
}

View File

@ -1,32 +0,0 @@
package org.postgresql.jdbc2;
import java.sql.*;
import java.util.Vector;
import org.postgresql.PGRefCursorResultSet;
import org.postgresql.core.BaseResultSet;
import org.postgresql.core.Field;
/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc2/Jdbc2Statement.java,v 1.7 2003/11/29 19:52:10 pgsql Exp $
* This class implements the java.sql.Statement interface for JDBC2.
* However most of the implementation is really done in
* org.postgresql.jdbc2.AbstractJdbc2Statement or one of it's parents
*/
public class Jdbc2Statement extends org.postgresql.jdbc2.AbstractJdbc2Statement implements java.sql.Statement
{
public Jdbc2Statement (Jdbc2Connection c)
{
super(c);
}
public BaseResultSet createResultSet (Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException
{
return new Jdbc2ResultSet(this, fields, tuples, status, updateCount, insertOID, binaryCursor);
}
public PGRefCursorResultSet createRefCursorResultSet (String cursorName) throws SQLException
{
return new Jdbc2RefCursorResultSet(this, cursorName);
}
}

View File

@ -1,48 +0,0 @@
package org.postgresql.jdbc2;
import org.postgresql.util.MessageTranslator;
/*
* This class extends java.sql.BatchUpdateException, and provides our
* internationalisation handling.
*/
class PBatchUpdateException extends java.sql.BatchUpdateException
{
private String message;
public PBatchUpdateException(
String error, Object arg1, Object arg2, int[] updateCounts )
{
super(updateCounts);
Object[] argv = new Object[2];
argv[0] = arg1;
argv[1] = arg2;
translate(error, argv);
}
private void translate(String error, Object[] args)
{
message = MessageTranslator.translate(error, args);
}
// Overides Throwable
public String getLocalizedMessage()
{
return message;
}
// Overides Throwable
public String getMessage()
{
return message;
}
// Overides Object
public String toString()
{
return message;
}
}

View File

@ -1,94 +0,0 @@
package org.postgresql.jdbc3;
import java.sql.*;
public abstract class AbstractJdbc3Blob extends org.postgresql.jdbc2.AbstractJdbc2Blob
{
public AbstractJdbc3Blob(org.postgresql.PGConnection conn, int oid) throws SQLException
{
super(conn, oid);
}
/**
* Writes the given array of bytes to the <code>BLOB</code> value that
* this <code>Blob</code> object represents, starting at position
* <code>pos</code>, and returns the number of bytes written.
*
* @param pos the position in the <code>BLOB</code> object at which
* to start writing
* @param bytes the array of bytes to be written to the <code>BLOB</code>
* value that this <code>Blob</code> object represents
* @return the number of bytes written
* @exception SQLException if there is an error accessing the
* <code>BLOB</code> value
* @see #getBytes
* @since 1.4
*/
public int setBytes(long pos, byte[] bytes) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Writes all or part of the given <code>byte</code> array to the
* <code>BLOB</code> value that this <code>Blob</code> object represents
* and returns the number of bytes written.
* Writing starts at position <code>pos</code> in the <code>BLOB</code>
* value; <code>len</code> bytes from the given byte array are written.
*
* @param pos the position in the <code>BLOB</code> object at which
* to start writing
* @param bytes the array of bytes to be written to this <code>BLOB</code>
* object
* @param offset the offset into the array <code>bytes</code> at which
* to start reading the bytes to be set
* @param len the number of bytes to be written to the <code>BLOB</code>
* value from the array of bytes <code>bytes</code>
* @return the number of bytes written
* @exception SQLException if there is an error accessing the
* <code>BLOB</code> value
* @see #getBytes
* @since 1.4
*/
public int setBytes(long pos, byte[] bytes, int offset, int len) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Retrieves a stream that can be used to write to the <code>BLOB</code>
* value that this <code>Blob</code> object represents. The stream begins
* at position <code>pos</code>.
*
* @param pos the position in the <code>BLOB</code> value at which
* to start writing
* @return a <code>java.io.OutputStream</code> object to which data can
* be written
* @exception SQLException if there is an error accessing the
* <code>BLOB</code> value
* @see #getBinaryStream
* @since 1.4
*/
public java.io.OutputStream setBinaryStream(long pos) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Truncates the <code>BLOB</code> value that this <code>Blob</code>
* object represents to be <code>len</code> bytes in length.
*
* @param len the length, in bytes, to which the <code>BLOB</code> value
* that this <code>Blob</code> object represents should be truncated
* @exception SQLException if there is an error accessing the
* <code>BLOB</code> value
* @since 1.4
*/
public void truncate(long len) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
}

View File

@ -1,112 +0,0 @@
package org.postgresql.jdbc3;
import java.sql.*;
public abstract class AbstractJdbc3Clob extends org.postgresql.jdbc2.AbstractJdbc2Clob
{
public AbstractJdbc3Clob(org.postgresql.PGConnection conn, int oid) throws SQLException
{
super(conn, oid);
}
/**
* Writes the given Java <code>String</code> to the <code>CLOB</code>
* value that this <code>Clob</code> object designates at the position
* <code>pos</code>.
*
* @param pos the position at which to start writing to the <code>CLOB</code>
* value that this <code>Clob</code> object represents
* @param str the string to be written to the <code>CLOB</code>
* value that this <code>Clob</code> designates
* @return the number of characters written
* @exception SQLException if there is an error accessing the
* <code>CLOB</code> value
*
* @since 1.4
*/
public int setString(long pos, String str) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Writes <code>len</code> characters of <code>str</code>, starting
* at character <code>offset</code>, to the <code>CLOB</code> value
* that this <code>Clob</code> represents.
*
* @param pos the position at which to start writing to this
* <code>CLOB</code> object
* @param str the string to be written to the <code>CLOB</code>
* value that this <code>Clob</code> object represents
* @param offset the offset into <code>str</code> to start reading
* the characters to be written
* @param len the number of characters to be written
* @return the number of characters written
* @exception SQLException if there is an error accessing the
* <code>CLOB</code> value
*
* @since 1.4
*/
public int setString(long pos, String str, int offset, int len) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Retrieves a stream to be used to write Ascii characters to the
* <code>CLOB</code> value that this <code>Clob</code> object represents,
* starting at position <code>pos</code>.
*
* @param pos the position at which to start writing to this
* <code>CLOB</code> object
* @return the stream to which ASCII encoded characters can be written
* @exception SQLException if there is an error accessing the
* <code>CLOB</code> value
* @see #getAsciiStream
*
* @since 1.4
*/
public java.io.OutputStream setAsciiStream(long pos) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Retrieves a stream to be used to write a stream of Unicode characters
* to the <code>CLOB</code> value that this <code>Clob</code> object
* represents, at position <code>pos</code>.
*
* @param pos the position at which to start writing to the
* <code>CLOB</code> value
*
* @return a stream to which Unicode encoded characters can be written
* @exception SQLException if there is an error accessing the
* <code>CLOB</code> value
* @see #getCharacterStream
*
* @since 1.4
*/
public java.io.Writer setCharacterStream(long pos) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Truncates the <code>CLOB</code> value that this <code>Clob</code>
* designates to have a length of <code>len</code>
* characters.
* @param len the length, in bytes, to which the <code>CLOB</code> value
* should be truncated
* @exception SQLException if there is an error accessing the
* <code>CLOB</code> value
*
* @since 1.4
*/
public void truncate(long len) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
}

View File

@ -1,459 +0,0 @@
package org.postgresql.jdbc3;
import java.sql.*;
/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc3/AbstractJdbc3Connection.java,v 1.5 2003/11/29 19:52:10 pgsql Exp $
* This class defines methods of the jdbc3 specification. This class extends
* org.postgresql.jdbc2.AbstractJdbc2Connection which provides the jdbc2
* methods. The real Connection class (for jdbc3) is org.postgresql.jdbc3.Jdbc3Connection
*/
public abstract class AbstractJdbc3Connection extends org.postgresql.jdbc2.AbstractJdbc2Connection
{
/**
* Changes the holdability of <code>ResultSet</code> objects
* created using this <code>Connection</code> object to the given
* holdability.
*
* @param holdability a <code>ResultSet</code> holdability constant; one of
* <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or
* <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>
* @throws SQLException if a database access occurs, the given parameter
* is not a <code>ResultSet</code> constant indicating holdability,
* or the given holdability is not supported
* @see #getHoldability
* @see ResultSet
* @since 1.4
*/
public void setHoldability(int holdability) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Retrieves the current holdability of <code>ResultSet</code> objects
* created using this <code>Connection</code> object.
*
* @return the holdability, one of
* <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or
* <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>
* @throws SQLException if a database access occurs
* @see #setHoldability
* @see ResultSet
* @since 1.4
*/
public int getHoldability() throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Creates an unnamed savepoint in the current transaction and
* returns the new <code>Savepoint</code> object that represents it.
*
* @return the new <code>Savepoint</code> object
* @exception SQLException if a database access error occurs
* or this <code>Connection</code> object is currently in
* auto-commit mode
* @see Savepoint
* @since 1.4
*/
public Savepoint setSavepoint() throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Creates a savepoint with the given name in the current transaction
* and returns the new <code>Savepoint</code> object that represents it.
*
* @param name a <code>String</code> containing the name of the savepoint
* @return the new <code>Savepoint</code> object
* @exception SQLException if a database access error occurs
* or this <code>Connection</code> object is currently in
* auto-commit mode
* @see Savepoint
* @since 1.4
*/
public Savepoint setSavepoint(String name) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Undoes all changes made after the given <code>Savepoint</code> object
* was set.
* <P>
* This method should be used only when auto-commit has been disabled.
*
* @param savepoint the <code>Savepoint</code> object to roll back to
* @exception SQLException if a database access error occurs,
* the <code>Savepoint</code> object is no longer valid,
* or this <code>Connection</code> object is currently in
* auto-commit mode
* @see Savepoint
* @see #rollback
* @since 1.4
*/
public void rollback(Savepoint savepoint) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Removes the given <code>Savepoint</code> object from the current
* transaction. Any reference to the savepoint after it have been removed
* will cause an <code>SQLException</code> to be thrown.
*
* @param savepoint the <code>Savepoint</code> object to be removed
* @exception SQLException if a database access error occurs or
* the given <code>Savepoint</code> object is not a valid
* savepoint in the current transaction
* @since 1.4
*/
public void releaseSavepoint(Savepoint savepoint) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Creates a <code>Statement</code> object that will generate
* <code>ResultSet</code> objects with the given type, concurrency,
* and holdability.
* This method is the same as the <code>createStatement</code> method
* above, but it allows the default result set
* type, concurrency, and holdability to be overridden.
*
* @param resultSetType one of the following <code>ResultSet</code>
* constants:
* <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or
* <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>
* @param resultSetConcurrency one of the following <code>ResultSet</code>
* constants:
* <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>
* @param resultSetHoldability one of the following <code>ResultSet</code>
* constants:
* <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or
* <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>
* @return a new <code>Statement</code> object that will generate
* <code>ResultSet</code> objects with the given type,
* concurrency, and holdability
* @exception SQLException if a database access error occurs
* or the given parameters are not <code>ResultSet</code>
* constants indicating type, concurrency, and holdability
* @see ResultSet
* @since 1.4
*/
public Statement createStatement(int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Creates a <code>PreparedStatement</code> object that will generate
* <code>ResultSet</code> objects with the given type, concurrency,
* and holdability.
* <P>
* This method is the same as the <code>prepareStatement</code> method
* above, but it allows the default result set
* type, concurrency, and holdability to be overridden.
*
* @param sql a <code>String</code> object that is the SQL statement to
* be sent to the database; may contain one or more ? IN
* parameters
* @param resultSetType one of the following <code>ResultSet</code>
* constants:
* <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or
* <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>
* @param resultSetConcurrency one of the following <code>ResultSet</code>
* constants:
* <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>
* @param resultSetHoldability one of the following <code>ResultSet</code>
* constants:
* <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or
* <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>
* @return a new <code>PreparedStatement</code> object, containing the
* pre-compiled SQL statement, that will generate
* <code>ResultSet</code> objects with the given type,
* concurrency, and holdability
* @exception SQLException if a database access error occurs
* or the given parameters are not <code>ResultSet</code>
* constants indicating type, concurrency, and holdability
* @see ResultSet
* @since 1.4
*/
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Creates a <code>CallableStatement</code> object that will generate
* <code>ResultSet</code> objects with the given type and concurrency.
* This method is the same as the <code>prepareCall</code> method
* above, but it allows the default result set
* type, result set concurrency type and holdability to be overridden.
*
* @param sql a <code>String</code> object that is the SQL statement to
* be sent to the database; may contain on or more ? parameters
* @param resultSetType one of the following <code>ResultSet</code>
* constants:
* <code>ResultSet.TYPE_FORWARD_ONLY</code>,
* <code>ResultSet.TYPE_SCROLL_INSENSITIVE</code>, or
* <code>ResultSet.TYPE_SCROLL_SENSITIVE</code>
* @param resultSetConcurrency one of the following <code>ResultSet</code>
* constants:
* <code>ResultSet.CONCUR_READ_ONLY</code> or
* <code>ResultSet.CONCUR_UPDATABLE</code>
* @param resultSetHoldability one of the following <code>ResultSet</code>
* constants:
* <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or
* <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>
* @return a new <code>CallableStatement</code> object, containing the
* pre-compiled SQL statement, that will generate
* <code>ResultSet</code> objects with the given type,
* concurrency, and holdability
* @exception SQLException if a database access error occurs
* or the given parameters are not <code>ResultSet</code>
* constants indicating type, concurrency, and holdability
* @see ResultSet
* @since 1.4
*/
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency,
int resultSetHoldability) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Creates a default <code>PreparedStatement</code> object that has
* the capability to retrieve auto-generated keys. The given constant
* tells the driver whether it should make auto-generated keys
* available for retrieval. This parameter is ignored if the SQL
* statement is not an <code>INSERT</code> statement.
* <P>
* <B>Note:</B> This method is optimized for handling
* parametric SQL statements that benefit from precompilation. If
* the driver supports precompilation,
* the method <code>prepareStatement</code> will send
* the statement to the database for precompilation. Some drivers
* may not support precompilation. In this case, the statement may
* not be sent to the database until the <code>PreparedStatement</code>
* object is executed. This has no direct effect on users; however, it does
* affect which methods throw certain SQLExceptions.
* <P>
* Result sets created using the returned <code>PreparedStatement</code>
* object will by default be type <code>TYPE_FORWARD_ONLY</code>
* and have a concurrency level of <code>CONCUR_READ_ONLY</code>.
*
* @param sql an SQL statement that may contain one or more '?' IN
* parameter placeholders
* @param autoGeneratedKeys a flag indicating whether auto-generated keys
* should be returned; one of the following <code>Statement</code>
* constants:
* @param autoGeneratedKeys a flag indicating that auto-generated keys should be returned, one of
* <code>Statement.RETURN_GENERATED_KEYS</code> or
* <code>Statement.NO_GENERATED_KEYS</code>.
* @return a new <code>PreparedStatement</code> object, containing the
* pre-compiled SQL statement, that will have the capability of
* returning auto-generated keys
* @exception SQLException if a database access error occurs
* or the given parameter is not a <code>Statement</code>
* constant indicating whether auto-generated keys should be
* returned
* @since 1.4
*/
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Creates a default <code>PreparedStatement</code> object capable
* of returning the auto-generated keys designated by the given array.
* This array contains the indexes of the columns in the target
* table that contain the auto-generated keys that should be made
* available. This array is ignored if the SQL
* statement is not an <code>INSERT</code> statement.
* <P>
* An SQL statement with or without IN parameters can be
* pre-compiled and stored in a <code>PreparedStatement</code> object. This
* object can then be used to efficiently execute this statement
* multiple times.
* <P>
* <B>Note:</B> This method is optimized for handling
* parametric SQL statements that benefit from precompilation. If
* the driver supports precompilation,
* the method <code>prepareStatement</code> will send
* the statement to the database for precompilation. Some drivers
* may not support precompilation. In this case, the statement may
* not be sent to the database until the <code>PreparedStatement</code>
* object is executed. This has no direct effect on users; however, it does
* affect which methods throw certain SQLExceptions.
* <P>
* Result sets created using the returned <code>PreparedStatement</code>
* object will by default be type <code>TYPE_FORWARD_ONLY</code>
* and have a concurrency level of <code>CONCUR_READ_ONLY</code>.
*
* @param sql an SQL statement that may contain one or more '?' IN
* parameter placeholders
* @param columnIndexes an array of column indexes indicating the columns
* that should be returned from the inserted row or rows
* @return a new <code>PreparedStatement</code> object, containing the
* pre-compiled statement, that is capable of returning the
* auto-generated keys designated by the given array of column
* indexes
* @exception SQLException if a database access error occurs
*
* @since 1.4
*/
public PreparedStatement prepareStatement(String sql, int columnIndexes[])
throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Creates a default <code>PreparedStatement</code> object capable
* of returning the auto-generated keys designated by the given array.
* This array contains the names of the columns in the target
* table that contain the auto-generated keys that should be returned.
* This array is ignored if the SQL
* statement is not an <code>INSERT</code> statement.
* <P>
* An SQL statement with or without IN parameters can be
* pre-compiled and stored in a <code>PreparedStatement</code> object. This
* object can then be used to efficiently execute this statement
* multiple times.
* <P>
* <B>Note:</B> This method is optimized for handling
* parametric SQL statements that benefit from precompilation. If
* the driver supports precompilation,
* the method <code>prepareStatement</code> will send
* the statement to the database for precompilation. Some drivers
* may not support precompilation. In this case, the statement may
* not be sent to the database until the <code>PreparedStatement</code>
* object is executed. This has no direct effect on users; however, it does
* affect which methods throw certain SQLExceptions.
* <P>
* Result sets created using the returned <code>PreparedStatement</code>
* object will by default be type <code>TYPE_FORWARD_ONLY</code>
* and have a concurrency level of <code>CONCUR_READ_ONLY</code>.
*
* @param sql an SQL statement that may contain one or more '?' IN
* parameter placeholders
* @param columnNames an array of column names indicating the columns
* that should be returned from the inserted row or rows
* @return a new <code>PreparedStatement</code> object, containing the
* pre-compiled statement, that is capable of returning the
* auto-generated keys designated by the given array of column
* names
* @exception SQLException if a database access error occurs
*
* @since 1.4
*/
public PreparedStatement prepareStatement(String sql, String columnNames[])
throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/*
* This implemetation uses the jdbc3Types array to support the jdbc3
* datatypes. Basically jdbc2 and jdbc3 are the same, except that
* jdbc3 adds some
*/
public int getSQLType(String pgTypeName)
{
int sqlType = Types.OTHER; // default value
for (int i = 0;i < jdbc3Types.length;i++)
{
if (pgTypeName.equals(jdbc3Types[i]))
{
sqlType = jdbc3Typei[i];
break;
}
}
return sqlType;
}
/*
* This table holds the org.postgresql names for the types supported.
* Any types that map to Types.OTHER (eg POINT) don't go into this table.
* They default automatically to Types.OTHER
*
* Note: This must be in the same order as below.
*
* Tip: keep these grouped together by the Types. value
*/
private static final String jdbc3Types[] = {
"int2",
"int4", "oid",
"int8",
"cash", "money",
"numeric",
"float4",
"float8",
"bpchar", "char", "char2", "char4", "char8", "char16",
"varchar", "text", "name", "filename",
"bytea",
"bool",
"bit",
"date",
"time",
"abstime", "timestamp", "timestamptz",
"_bool", "_char", "_int2", "_int4", "_text",
"_oid", "_varchar", "_int8", "_float4", "_float8",
"_abstime", "_date", "_time", "_timestamp", "_numeric",
"_bytea"
};
/*
* This table holds the JDBC type for each entry above.
*
* Note: This must be in the same order as above
*
* Tip: keep these grouped together by the Types. value
*/
private static final int jdbc3Typei[] = {
Types.SMALLINT,
Types.INTEGER, Types.INTEGER,
Types.BIGINT,
Types.DOUBLE, Types.DOUBLE,
Types.NUMERIC,
Types.REAL,
Types.DOUBLE,
Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR, Types.CHAR,
Types.VARCHAR, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
Types.BINARY,
Types.BIT,
Types.BIT,
Types.DATE,
Types.TIME,
Types.TIMESTAMP, Types.TIMESTAMP, Types.TIMESTAMP,
Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY,
Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY,
Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY, Types.ARRAY,
Types.ARRAY
};
}

View File

@ -1,355 +0,0 @@
package org.postgresql.jdbc3;
import java.sql.*;
public abstract class AbstractJdbc3DatabaseMetaData extends org.postgresql.jdbc2.AbstractJdbc2DatabaseMetaData
{
public AbstractJdbc3DatabaseMetaData(AbstractJdbc3Connection conn)
{
super(conn);
}
/**
* Retrieves whether this database supports savepoints.
*
* @return <code>true</code> if savepoints are supported;
* <code>false</code> otherwise
* @exception SQLException if a database access error occurs
* @since 1.4
*/
public boolean supportsSavepoints() throws SQLException
{
return false;
}
/**
* Retrieves whether this database supports named parameters to callable
* statements.
*
* @return <code>true</code> if named parameters are supported;
* <code>false</code> otherwise
* @exception SQLException if a database access error occurs
* @since 1.4
*/
public boolean supportsNamedParameters() throws SQLException
{
return false;
}
/**
* Retrieves whether it is possible to have multiple <code>ResultSet</code> objects
* returned from a <code>CallableStatement</code> object
* simultaneously.
*
* @return <code>true</code> if a <code>CallableStatement</code> object
* can return multiple <code>ResultSet</code> objects
* simultaneously; <code>false</code> otherwise
* @exception SQLException if a datanase access error occurs
* @since 1.4
*/
public boolean supportsMultipleOpenResults() throws SQLException
{
return false;
}
/**
* Retrieves whether auto-generated keys can be retrieved after
* a statement has been executed.
*
* @return <code>true</code> if auto-generated keys can be retrieved
* after a statement has executed; <code>false</code> otherwise
* @exception SQLException if a database access error occurs
* @since 1.4
*/
public boolean supportsGetGeneratedKeys() throws SQLException
{
return false;
}
/**
* Retrieves a description of the user-defined type (UDT) hierarchies defined in a
* particular schema in this database. Only the immediate super type/
* sub type relationship is modeled.
* <P>
* Only supertype information for UDTs matching the catalog,
* schema, and type name is returned. The type name parameter
* may be a fully-qualified name. When the UDT name supplied is a
* fully-qualified name, the catalog and schemaPattern parameters are
* ignored.
* <P>
* If a UDT does not have a direct super type, it is not listed here.
* A row of the <code>ResultSet</code> object returned by this method
* describes the designated UDT and a direct supertype. A row has the following
* columns:
* <OL>
* <LI><B>TYPE_CAT</B> String => the UDT's catalog (may be <code>null</code>)
* <LI><B>TYPE_SCHEM</B> String => UDT's schema (may be <code>null</code>)
* <LI><B>TYPE_NAME</B> String => type name of the UDT
* <LI><B>SUPERTYPE_CAT</B> String => the direct super type's catalog
* (may be <code>null</code>)
* <LI><B>SUPERTYPE_SCHEM</B> String => the direct super type's schema
* (may be <code>null</code>)
* <LI><B>SUPERTYPE_NAME</B> String => the direct super type's name
* </OL>
*
* <P><B>Note:</B> If the driver does not support type hierarchies, an
* empty result set is returned.
*
* @param catalog a catalog name; "" retrieves those without a catalog;
* <code>null</code> means drop catalog name from the selection criteria
* @param schemaPattern a schema name pattern; "" retrieves those
* without a schema
* @param typeNamePattern a UDT name pattern; may be a fully-qualified
* name
* @return a <code>ResultSet</code> object in which a row gives information
* about the designated UDT
* @throws SQLException if a database access error occurs
* @since 1.4
*/
public ResultSet getSuperTypes(String catalog, String schemaPattern,
String typeNamePattern) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Retrieves a description of the table hierarchies defined in a particular
* schema in this database.
*
* <P>Only supertable information for tables matching the catalog, schema
* and table name are returned. The table name parameter may be a fully-
* qualified name, in which case, the catalog and schemaPattern parameters
* are ignored. If a table does not have a super table, it is not listed here.
* Supertables have to be defined in the same catalog and schema as the
* sub tables. Therefore, the type description does not need to include
* this information for the supertable.
*
* <P>Each type description has the following columns:
* <OL>
* <LI><B>TABLE_CAT</B> String => the type's catalog (may be <code>null</code>)
* <LI><B>TABLE_SCHEM</B> String => type's schema (may be <code>null</code>)
* <LI><B>TABLE_NAME</B> String => type name
* <LI><B>SUPERTABLE_NAME</B> String => the direct super type's name
* </OL>
*
* <P><B>Note:</B> If the driver does not support type hierarchies, an
* empty result set is returned.
*
* @param catalog a catalog name; "" retrieves those without a catalog;
* <code>null</code> means drop catalog name from the selection criteria
* @param schemaPattern a schema name pattern; "" retrieves those
* without a schema
* @param tableNamePattern a table name pattern; may be a fully-qualified
* name
* @return a <code>ResultSet</code> object in which each row is a type description
* @throws SQLException if a database access error occurs
* @since 1.4
*/
public ResultSet getSuperTables(String catalog, String schemaPattern,
String tableNamePattern) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Retrieves a description of the given attribute of the given type
* for a user-defined type (UDT) that is available in the given schema
* and catalog.
* <P>
* Descriptions are returned only for attributes of UDTs matching the
* catalog, schema, type, and attribute name criteria. They are ordered by
* TYPE_SCHEM, TYPE_NAME and ORDINAL_POSITION. This description
* does not contain inherited attributes.
* <P>
* The <code>ResultSet</code> object that is returned has the following
* columns:
* <OL>
* <LI><B>TYPE_CAT</B> String => type catalog (may be <code>null</code>)
* <LI><B>TYPE_SCHEM</B> String => type schema (may be <code>null</code>)
* <LI><B>TYPE_NAME</B> String => type name
* <LI><B>ATTR_NAME</B> String => attribute name
* <LI><B>DATA_TYPE</B> short => attribute type SQL type from java.sql.Types
* <LI><B>ATTR_TYPE_NAME</B> String => Data source dependent type name.
* For a UDT, the type name is fully qualified. For a REF, the type name is
* fully qualified and represents the target type of the reference type.
* <LI><B>ATTR_SIZE</B> int => column size. For char or date
* types this is the maximum number of characters; for numeric or
* decimal types this is precision.
* <LI><B>DECIMAL_DIGITS</B> int => the number of fractional digits
* <LI><B>NUM_PREC_RADIX</B> int => Radix (typically either 10 or 2)
* <LI><B>NULLABLE</B> int => whether NULL is allowed
* <UL>
* <LI> attributeNoNulls - might not allow NULL values
* <LI> attributeNullable - definitely allows NULL values
* <LI> attributeNullableUnknown - nullability unknown
* </UL>
* <LI><B>REMARKS</B> String => comment describing column (may be <code>null</code>)
* <LI><B>ATTR_DEF</B> String => default value (may be <code>null</code>)
* <LI><B>SQL_DATA_TYPE</B> int => unused
* <LI><B>SQL_DATETIME_SUB</B> int => unused
* <LI><B>CHAR_OCTET_LENGTH</B> int => for char types the
* maximum number of bytes in the column
* <LI><B>ORDINAL_POSITION</B> int => index of column in table
* (starting at 1)
* <LI><B>IS_NULLABLE</B> String => "NO" means column definitely
* does not allow NULL values; "YES" means the column might
* allow NULL values. An empty string means unknown.
* <LI><B>SCOPE_CATALOG</B> String => catalog of table that is the
* scope of a reference attribute (<code>null</code> if DATA_TYPE isn't REF)
* <LI><B>SCOPE_SCHEMA</B> String => schema of table that is the
* scope of a reference attribute (<code>null</code> if DATA_TYPE isn't REF)
* <LI><B>SCOPE_TABLE</B> String => table name that is the scope of a
* reference attribute (<code>null</code> if the DATA_TYPE isn't REF)
* <LI><B>SOURCE_DATA_TYPE</B> short => source type of a distinct type or user-generated
* Ref type,SQL type from java.sql.Types (<code>null</code> if DATA_TYPE
* isn't DISTINCT or user-generated REF)
* </OL>
* @param catalog a catalog name; must match the catalog name as it
* is stored in the database; "" retrieves those without a catalog;
* <code>null</code> means that the catalog name should not be used to narrow
* the search
* @param schemaPattern a schema name pattern; must match the schema name
* as it is stored in the database; "" retrieves those without a schema;
* <code>null</code> means that the schema name should not be used to narrow
* the search
* @param typeNamePattern a type name pattern; must match the
* type name as it is stored in the database
* @param attributeNamePattern an attribute name pattern; must match the attribute
* name as it is declared in the database
* @return a <code>ResultSet</code> object in which each row is an
* attribute description
* @exception SQLException if a database access error occurs
* @since 1.4
*/
public ResultSet getAttributes(String catalog, String schemaPattern,
String typeNamePattern, String attributeNamePattern)
throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Retrieves whether this database supports the given result set holdability.
*
* @param holdability one of the following constants:
* <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or
* <code>ResultSet.CLOSE_CURSORS_AT_COMMIT<code>
* @return <code>true</code> if so; <code>false</code> otherwise
* @exception SQLException if a database access error occurs
* @see Connection
* @since 1.4
*/
public boolean supportsResultSetHoldability(int holdability) throws SQLException
{
return true;
}
/**
* Retrieves the default holdability of this <code>ResultSet</code>
* object.
*
* @return the default holdability; either
* <code>ResultSet.HOLD_CURSORS_OVER_COMMIT</code> or
* <code>ResultSet.CLOSE_CURSORS_AT_COMMIT</code>
* @exception SQLException if a database access error occurs
* @since 1.4
*/
public int getResultSetHoldability() throws SQLException
{
return ResultSet.HOLD_CURSORS_OVER_COMMIT;
}
/**
* Retrieves the major version number of the underlying database.
*
* @return the underlying database's major version
* @exception SQLException if a database access error occurs
* @since 1.4
*/
public int getDatabaseMajorVersion() throws SQLException
{
return connection.getServerMajorVersion();
}
/**
* Retrieves the minor version number of the underlying database.
*
* @return underlying database's minor version
* @exception SQLException if a database access error occurs
* @since 1.4
*/
public int getDatabaseMinorVersion() throws SQLException
{
return connection.getServerMinorVersion();
}
/**
* Retrieves the major JDBC version number for this
* driver.
*
* @return JDBC version major number
* @exception SQLException if a database access error occurs
* @since 1.4
*/
public int getJDBCMajorVersion() throws SQLException
{
return 3; // This class implements JDBC 3.0
}
/**
* Retrieves the minor JDBC version number for this
* driver.
*
* @return JDBC version minor number
* @exception SQLException if a database access error occurs
* @since 1.4
*/
public int getJDBCMinorVersion() throws SQLException
{
return 0; // This class implements JDBC 3.0
}
/**
* Indicates whether the SQLSTATEs returned by <code>SQLException.getSQLState</code>
* is X/Open (now known as Open Group) SQL CLI or SQL99.
* @return the type of SQLSTATEs, one of:
* sqlStateXOpen or
* sqlStateSQL99
* @throws SQLException if a database access error occurs
* @since 1.4
*/
public int getSQLStateType() throws SQLException
{
return DatabaseMetaData.sqlStateSQL99;
}
/**
* Indicates whether updates made to a LOB are made on a copy or directly
* to the LOB.
* @return <code>true</code> if updates are made to a copy of the LOB;
* <code>false</code> if updates are made directly to the LOB
* @throws SQLException if a database access error occurs
* @since 1.4
*/
public boolean locatorsUpdateCopy() throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Retrieves weather this database supports statement pooling.
*
* @return <code>true</code> is so;
<code>false</code> otherwise
* @throws SQLExcpetion if a database access error occurs
* @since 1.4
*/
public boolean supportsStatementPooling() throws SQLException
{
return false;
}
}

View File

@ -1,196 +0,0 @@
package org.postgresql.jdbc3;
import java.sql.*;
import java.util.Vector;
import org.postgresql.core.BaseStatement;
import org.postgresql.core.Field;
/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc3/AbstractJdbc3ResultSet.java,v 1.5 2003/11/29 19:52:11 pgsql Exp $
* This class defines methods of the jdbc3 specification. This class extends
* org.postgresql.jdbc2.AbstractJdbc2ResultSet which provides the jdbc2
* methods. The real Statement class (for jdbc3) is org.postgresql.jdbc3.Jdbc3ResultSet
*/
public abstract class AbstractJdbc3ResultSet extends org.postgresql.jdbc2.AbstractJdbc2ResultSet
{
public AbstractJdbc3ResultSet(BaseStatement statement, Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor)
{
super (statement, fields, tuples, status, updateCount, insertOID, binaryCursor);
}
/**
* Retrieves the value of the designated column in the current row
* of this <code>ResultSet</code> object as a <code>java.net.URL</code>
* object in the Java programming language.
*
* @param columnIndex the index of the column 1 is the first, 2 is the second,...
* @return the column value as a <code>java.net.URL</code> object;
* if the value is SQL <code>NULL</code>,
* the value returned is <code>null</code> in the Java programming language
* @exception SQLException if a database access error occurs,
* or if a URL is malformed
* @since 1.4
*/
public java.net.URL getURL(int columnIndex) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Retrieves the value of the designated column in the current row
* of this <code>ResultSet</code> object as a <code>java.net.URL</code>
* object in the Java programming language.
*
* @param columnName the SQL name of the column
* @return the column value as a <code>java.net.URL</code> object;
* if the value is SQL <code>NULL</code>,
* the value returned is <code>null</code> in the Java programming language
* @exception SQLException if a database access error occurs
* or if a URL is malformed
* @since 1.4
*/
public java.net.URL getURL(String columnName) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Updates the designated column with a <code>java.sql.Ref</code> value.
* The updater methods are used to update column values in the
* current row or the insert row. The updater methods do not
* update the underlying database; instead the <code>updateRow</code> or
* <code>insertRow</code> methods are called to update the database.
*
* @param columnIndex the first column is 1, the second is 2, ...
* @param x the new column value
* @exception SQLException if a database access error occurs
* @since 1.4
*/
public void updateRef(int columnIndex, java.sql.Ref x) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Updates the designated column with a <code>java.sql.Ref</code> value.
* The updater methods are used to update column values in the
* current row or the insert row. The updater methods do not
* update the underlying database; instead the <code>updateRow</code> or
* <code>insertRow</code> methods are called to update the database.
*
* @param columnName the name of the column
* @param x the new column value
* @exception SQLException if a database access error occurs
* @since 1.4
*/
public void updateRef(String columnName, java.sql.Ref x) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Updates the designated column with a <code>java.sql.Blob</code> value.
* The updater methods are used to update column values in the
* current row or the insert row. The updater methods do not
* update the underlying database; instead the <code>updateRow</code> or
* <code>insertRow</code> methods are called to update the database.
*
* @param columnIndex the first column is 1, the second is 2, ...
* @param x the new column value
* @exception SQLException if a database access error occurs
* @since 1.4
*/
public void updateBlob(int columnIndex, java.sql.Blob x) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Updates the designated column with a <code>java.sql.Blob</code> value.
* The updater methods are used to update column values in the
* current row or the insert row. The updater methods do not
* update the underlying database; instead the <code>updateRow</code> or
* <code>insertRow</code> methods are called to update the database.
*
* @param columnName the name of the column
* @param x the new column value
* @exception SQLException if a database access error occurs
* @since 1.4
*/
public void updateBlob(String columnName, java.sql.Blob x) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Updates the designated column with a <code>java.sql.Clob</code> value.
* The updater methods are used to update column values in the
* current row or the insert row. The updater methods do not
* update the underlying database; instead the <code>updateRow</code> or
* <code>insertRow</code> methods are called to update the database.
*
* @param columnIndex the first column is 1, the second is 2, ...
* @param x the new column value
* @exception SQLException if a database access error occurs
* @since 1.4
*/
public void updateClob(int columnIndex, java.sql.Clob x) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Updates the designated column with a <code>java.sql.Clob</code> value.
* The updater methods are used to update column values in the
* current row or the insert row. The updater methods do not
* update the underlying database; instead the <code>updateRow</code> or
* <code>insertRow</code> methods are called to update the database.
*
* @param columnName the name of the column
* @param x the new column value
* @exception SQLException if a database access error occurs
* @since 1.4
*/
public void updateClob(String columnName, java.sql.Clob x) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Updates the designated column with a <code>java.sql.Array</code> value.
* The updater methods are used to update column values in the
* current row or the insert row. The updater methods do not
* update the underlying database; instead the <code>updateRow</code> or
* <code>insertRow</code> methods are called to update the database.
*
* @param columnIndex the first column is 1, the second is 2, ...
* @param x the new column value
* @exception SQLException if a database access error occurs
* @since 1.4
*/
public void updateArray(int columnIndex, java.sql.Array x) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
/**
* Updates the designated column with a <code>java.sql.Array</code> value.
* The updater methods are used to update column values in the
* current row or the insert row. The updater methods do not
* update the underlying database; instead the <code>updateRow</code> or
* <code>insertRow</code> methods are called to update the database.
*
* @param columnName the name of the column
* @param x the new column value
* @exception SQLException if a database access error occurs
* @since 1.4
*/
public void updateArray(String columnName, java.sql.Array x) throws SQLException
{
throw org.postgresql.Driver.notImplemented();
}
}

View File

@ -1,14 +0,0 @@
package org.postgresql.jdbc3;
import java.sql.*;
public class Jdbc3Blob extends org.postgresql.jdbc3.AbstractJdbc3Blob implements java.sql.Blob
{
public Jdbc3Blob(org.postgresql.PGConnection conn, int oid) throws SQLException
{
super(conn, oid);
}
}

View File

@ -1,28 +0,0 @@
package org.postgresql.jdbc3;
import java.sql.*;
import java.util.Vector;
import org.postgresql.PGRefCursorResultSet;
import org.postgresql.core.BaseResultSet;
import org.postgresql.core.Field;
public class Jdbc3CallableStatement extends org.postgresql.jdbc3.AbstractJdbc3Statement implements java.sql.CallableStatement
{
public Jdbc3CallableStatement(Jdbc3Connection connection, String sql) throws SQLException
{
super(connection, sql);
}
public BaseResultSet createResultSet (Field[] fields, Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException
{
return new Jdbc3ResultSet(this, fields, tuples, status, updateCount, insertOID, binaryCursor);
}
public PGRefCursorResultSet createRefCursorResultSet (String cursorName) throws SQLException
{
return new Jdbc3RefCursorResultSet(this, cursorName);
}
}

View File

@ -1,12 +0,0 @@
package org.postgresql.jdbc3;
public class Jdbc3Clob extends org.postgresql.jdbc3.AbstractJdbc3Clob implements java.sql.Clob
{
public Jdbc3Clob(org.postgresql.PGConnection conn, int oid) throws java.sql.SQLException
{
super(conn, oid);
}
}

View File

@ -1,46 +0,0 @@
package org.postgresql.jdbc3;
import java.sql.SQLException;
/* $PostgreSQL: pgsql/src/interfaces/jdbc/org/postgresql/jdbc3/Jdbc3Connection.java,v 1.6 2003/11/29 19:52:11 pgsql Exp $
* This class implements the java.sql.Connection interface for JDBC3.
* However most of the implementation is really done in
* org.postgresql.jdbc3.AbstractJdbc3Connection or one of it's parents
*/
public class Jdbc3Connection extends org.postgresql.jdbc3.AbstractJdbc3Connection implements java.sql.Connection
{
public java.sql.Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException
{
Jdbc3Statement s = new Jdbc3Statement(this);
s.setResultSetType(resultSetType);
s.setResultSetConcurrency(resultSetConcurrency);
return s;
}
public java.sql.PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{
Jdbc3PreparedStatement s = new Jdbc3PreparedStatement(this, sql);
s.setResultSetType(resultSetType);
s.setResultSetConcurrency(resultSetConcurrency);
return s;
}
public java.sql.CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException
{
Jdbc3CallableStatement s = new Jdbc3CallableStatement(this, sql);
s.setResultSetType(resultSetType);
s.setResultSetConcurrency(resultSetConcurrency);
return s;
}
public java.sql.DatabaseMetaData getMetaData() throws SQLException
{
if (metadata == null)
metadata = new Jdbc3DatabaseMetaData(this);
return metadata;
}
}

View File

@ -1,61 +0,0 @@
package org.postgresql.jdbc3;
import org.postgresql.jdbc2.optional.ConnectionPool;
import javax.sql.PooledConnection;
import javax.naming.Reference;
import java.sql.SQLException;
/**
* Jdbc3 implementation of ConnectionPoolDataSource. This is
* typically the interface used by an app server to interact
* with connection pools provided by a JDBC driver. PostgreSQL
* does not support XADataSource, the other common connection
* pooling interface (for connections supporting the two-phase
* commit protocol).
*
* @author Aaron Mulder (ammulder@alumni.princeton.edu)
* @version $Revision: 1.1 $
*/
public class Jdbc3ConnectionPool extends ConnectionPool
{
/**
* Gets a description of this DataSource.
*/
public String getDescription()
{
return "Jdbc3ConnectionPool from " + org.postgresql.Driver.getVersion();
}
/**
* Gets a connection which may be pooled by the app server or middleware
* implementation of DataSource.
*
* @throws java.sql.SQLException
* Occurs when the physical database connection cannot be established.
*/
public PooledConnection getPooledConnection() throws SQLException
{
return new Jdbc3PooledConnection(getConnection(), isDefaultAutoCommit());
}
/**
* Gets a connection which may be pooled by the app server or middleware
* implementation of DataSource.
*
* @throws java.sql.SQLException
* Occurs when the physical database connection cannot be established.
*/
public PooledConnection getPooledConnection(String user, String password) throws SQLException
{
return new Jdbc3PooledConnection(getConnection(user, password), isDefaultAutoCommit());
}
/**
* Generates a JDBC object factory reference.
*/
protected Reference createReference()
{
return new Reference(getClass().getName(), Jdbc3ObjectFactory.class.getName(), null);
}
}

View File

@ -1,12 +0,0 @@
package org.postgresql.jdbc3;
public class Jdbc3DatabaseMetaData extends org.postgresql.jdbc3.AbstractJdbc3DatabaseMetaData implements java.sql.DatabaseMetaData
{
public Jdbc3DatabaseMetaData(Jdbc3Connection conn)
{
super(conn);
}
}

View File

@ -1,80 +0,0 @@
package org.postgresql.jdbc3;
import java.util.*;
import javax.naming.*;
import org.postgresql.jdbc2.optional.PGObjectFactory;
/**
* JDBC3 version of the Object Factory used to recreate objects
* from their JNDI references.
*
* @author Aaron Mulder (ammulder@alumni.princeton.edu)
* @version $Revision: 1.1 $
*/
public class Jdbc3ObjectFactory extends PGObjectFactory
{
/**
* Dereferences a PostgreSQL DataSource. Other types of references are
* ignored.
*/
public Object getObjectInstance(Object obj, Name name, Context nameCtx,
Hashtable environment) throws Exception
{
Reference ref = (Reference) obj;
if (ref.getClassName().equals(Jdbc3SimpleDataSource.class.getName()))
{
return loadSimpleDataSource(ref);
}
else if (ref.getClassName().equals(Jdbc3ConnectionPool.class.getName()))
{
return loadConnectionPool(ref);
}
else if (ref.getClassName().equals(Jdbc3PoolingDataSource.class.getName()))
{
return loadPoolingDataSource(ref);
}
else
{
return null;
}
}
private Object loadPoolingDataSource(Reference ref)
{
// If DataSource exists, return it
String name = getProperty(ref, "dataSourceName");
Jdbc3PoolingDataSource pds = Jdbc3PoolingDataSource.getDataSource(name);
if (pds != null)
{
return pds;
}
// Otherwise, create a new one
pds = new Jdbc3PoolingDataSource();
pds.setDataSourceName(name);
loadBaseDataSource(pds, ref);
String min = getProperty(ref, "initialConnections");
if (min != null)
{
pds.setInitialConnections(Integer.parseInt(min));
}
String max = getProperty(ref, "maxConnections");
if (max != null)
{
pds.setMaxConnections(Integer.parseInt(max));
}
return pds;
}
private Object loadSimpleDataSource(Reference ref)
{
Jdbc3SimpleDataSource ds = new Jdbc3SimpleDataSource();
return loadBaseDataSource(ds, ref);
}
private Object loadConnectionPool(Reference ref)
{
Jdbc3ConnectionPool cp = new Jdbc3ConnectionPool();
return loadBaseDataSource(cp, ref);
}
}

View File

@ -1,20 +0,0 @@
package org.postgresql.jdbc3;
import org.postgresql.jdbc2.optional.PooledConnectionImpl;
import java.sql.Connection;
/**
* JDBC3 implementation of PooledConnection, which manages
* a connection in a connection pool.
*
* @author Aaron Mulder (ammulder@alumni.princeton.edu)
* @version $Revision: 1.1 $
*/
public class Jdbc3PooledConnection extends PooledConnectionImpl
{
Jdbc3PooledConnection(Connection con, boolean autoCommit)
{
super(con, autoCommit);
}
}

View File

@ -1,96 +0,0 @@
package org.postgresql.jdbc3;
import java.util.*;
import org.postgresql.jdbc2.optional.PoolingDataSource;
import org.postgresql.jdbc2.optional.ConnectionPool;
import javax.naming.Reference;
/**
* JDBC 3 implementation of a pooling DataSource. This is best
* used outside of an application server environment. Application
* servers generally prefer to deal with instances of
* ConnectionPoolDataSource (see ConnectionPool) or XADataSource
* (not available for PostgreSQL).
*
* @author Aaron Mulder (ammulder@alumni.princeton.edu)
* @version $Revision: 1.1 $
*/
public class Jdbc3PoolingDataSource extends PoolingDataSource
{
/**
* Store JDBC3 DataSources in different bucket than JDBC2 DataSources
*/
private static Map dataSources = new HashMap();
/**
* Store JDBC3 DataSources in different bucket than JDBC2 DataSources
*/
static Jdbc3PoolingDataSource getDataSource(String name)
{
return (Jdbc3PoolingDataSource) dataSources.get(name);
}
/**
* Store JDBC3 DataSources in different bucket than JDBC2 DataSources
*/
protected void removeStoredDataSource()
{
synchronized (dataSources)
{
dataSources.remove(dataSourceName);
}
}
/**
* Store JDBC3 DataSources in different bucket than JDBC2 DataSources
*/
public void setDataSourceName(String dataSourceName)
{
if (isInitialized())
{
throw new IllegalStateException("Cannot set Data Source properties after DataSource has been used");
}
if (this.dataSourceName != null && dataSourceName != null && dataSourceName.equals(this.dataSourceName))
{
return;
}
synchronized (dataSources)
{
if (getDataSource(dataSourceName) != null)
{
throw new IllegalArgumentException("DataSource with name '" + dataSourceName + "' already exists!");
}
if (this.dataSourceName != null)
{
dataSources.remove(this.dataSourceName);
}
this.dataSourceName = dataSourceName;
dataSources.put(dataSourceName, this);
}
}
/**
* Generates a JDBC3 object factory reference.
*/
protected Reference createReference()
{
return new Reference(getClass().getName(), Jdbc3ObjectFactory.class.getName(), null);
}
/**
* Creates a JDBC3 ConnectionPool to use with this DataSource.
*/
protected ConnectionPool createConnectionPool()
{
return new Jdbc3ConnectionPool();
}
/**
* Gets a description of this DataSource.
*/
public String getDescription()
{
return "JDBC3 Pooling DataSource from " + org.postgresql.Driver.getVersion();
}
}

View File

@ -1,28 +0,0 @@
package org.postgresql.jdbc3;
import java.sql.*;
import org.postgresql.PGRefCursorResultSet;
import org.postgresql.core.BaseResultSet;
import org.postgresql.core.BaseStatement;
import org.postgresql.core.Field;
public class Jdbc3PreparedStatement extends org.postgresql.jdbc3.AbstractJdbc3Statement implements java.sql.PreparedStatement
{
public Jdbc3PreparedStatement(Jdbc3Connection connection, String sql) throws SQLException
{
super(connection, sql);
}
public BaseResultSet createResultSet (Field[] fields, java.util.Vector tuples, String status, int updateCount, long insertOID, boolean binaryCursor) throws SQLException
{
return new Jdbc3ResultSet((BaseStatement)this, fields, tuples, status, updateCount, insertOID, binaryCursor);
}
public PGRefCursorResultSet createRefCursorResultSet (String cursorName) throws SQLException
{
return new Jdbc3RefCursorResultSet(this, cursorName);
}
}

View File

@ -1,46 +0,0 @@
package org.postgresql.jdbc3;
import org.postgresql.PGRefCursorResultSet;
import org.postgresql.core.BaseStatement;
import org.postgresql.core.Field;
import org.postgresql.core.QueryExecutor;
import java.util.Vector;
/** A real result set based on a ref cursor.
*
* @author Nic Ferrier <nferrier@tapsellferrier.co.uk>
*/
public class Jdbc3RefCursorResultSet extends Jdbc3ResultSet implements PGRefCursorResultSet
{
String refCursorHandle;
// Indicates when the result set has activaly bound to the cursor.
boolean isInitialized = false;
Jdbc3RefCursorResultSet(java.sql.Statement statement, String refCursorName) throws java.sql.SQLException
{
// This casting is a GCJ requirement.
super((BaseStatement)statement,
(Field[])null,
(Vector)null,
(String)null, -1, 0L, false);
this.refCursorHandle = refCursorName;
}
public String getRefCursor ()
{
return refCursorHandle;
}
public boolean next () throws java.sql.SQLException
{
if (isInitialized)
return super.next();
// Initialize this res set with the rows from the cursor.
String[] toExec = { "FETCH ALL IN \"" + refCursorHandle + "\";" };
QueryExecutor.execute(toExec, new String[0], this);
isInitialized = true;
return super.next();
}
}

Some files were not shown because too many files have changed in this diff Show More