Reworked samples so that no default passwords are defined anywhere; added

Python script to create sample schemas and drop them in addition to having a
SQL*Plus script.
This commit is contained in:
Anthony Tuininga 2019-01-31 10:15:40 -07:00
parent b8d5479048
commit 81583c224d
45 changed files with 865 additions and 648 deletions

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
@ -26,7 +26,7 @@ import SampleEnv
import decimal
# connect to database
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
cursor = connection.cursor()
# dequeue all existing messages to ensure the queue is empty, just so that

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -31,7 +31,7 @@ def callback(message):
print("Queue name:", message.queueName)
print("Consumer name:", message.consumerName)
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING, events = True)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString(), events = True)
sub = connection.subscribe(namespace = cx_Oracle.SUBSCR_NAMESPACE_AQ,
name = "BOOKS", callback = callback, timeout = 300)
print("Subscription:", sub)

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
@ -29,7 +29,7 @@ APP_CTX_ENTRIES = [
( APP_CTX_NAMESPACE, "ATTR3", "VALUE3" )
]
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING,
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString(),
appcontext = APP_CTX_ENTRIES)
cursor = connection.cursor()
for namespace, name, value in APP_CTX_ENTRIES:

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -18,7 +18,7 @@ from __future__ import print_function
import cx_Oracle
import SampleEnv
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
cursor = connection.cursor()
# show the number of rows for each parent ID as a means of verifying the

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -20,7 +20,7 @@ from __future__ import print_function
import cx_Oracle
import SampleEnv
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
cursor = connection.cursor()
# define data to insert

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -13,7 +13,7 @@ from __future__ import print_function
import cx_Oracle
import SampleEnv
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
rows = [ (1, "First" ),
(2, "Second" ),

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -17,7 +17,7 @@ from __future__ import print_function
import cx_Oracle
import SampleEnv
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
cursor = connection.cursor()
sql = 'select * from SampleQueryTab where id = :bvid'

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
@ -50,7 +50,7 @@ def callback(message):
print("-" * 60)
print("=" * 60)
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING, events = True)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString(), events = True)
sub = connection.subscribe(callback = callback, timeout = 1800,
qos = cx_Oracle.SUBSCR_QOS_QUERY | cx_Oracle.SUBSCR_QOS_ROWIDS)
print("Subscription:", sub)

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
@ -22,7 +22,7 @@ import datetime
import SampleEnv
# truncate table first so that script can be rerun
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
cursor = connection.cursor()
print("Truncating table...")
cursor.execute("truncate table TestTempTable")

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
@ -33,7 +33,7 @@ from __future__ import print_function
import cx_Oracle
import SampleEnv
conn = cx_Oracle.connect(SampleEnv.DRCP_CONNECT_STRING, cclass = "PYCLASS",
conn = cx_Oracle.connect(SampleEnv.GetDrcpConnectString(), cclass = "PYCLASS",
purity = cx_Oracle.ATTR_PURITY_SELF)
cursor = conn.cursor()
print("Performing query using DRCP...")

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
@ -47,7 +47,7 @@ def callback(message):
print("-" * 60)
print("=" * 60)
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING, events = True)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString(), events = True)
sub = connection.subscribe(callback = callback, timeout = 1800,
qos = cx_Oracle.SUBSCR_QOS_ROWIDS)
print("Subscription:", sub)

28
samples/DropSamples.py Normal file
View File

@ -0,0 +1,28 @@
#------------------------------------------------------------------------------
# Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# DropSamples.py
#
# Drops the database objects used for the cx_Oracle samples.
#------------------------------------------------------------------------------
from __future__ import print_function
import cx_Oracle
import SampleEnv
def DropSamples(conn):
print("Dropping sample schemas and edition...")
SampleEnv.RunSqlScript(conn, "DropSamples",
main_user = SampleEnv.GetMainUser(),
edition_user = SampleEnv.GetEditionUser(),
edition_name = SampleEnv.GetEditionName())
if __name__ == "__main__":
conn = cx_Oracle.connect(SampleEnv.GetSysdbaConnectString(),
mode = cx_Oracle.SYSDBA)
DropSamples(conn)
print("Done.")

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
@ -24,7 +24,8 @@ import SampleEnv
import os
# connect to the editions user and create a procedure
connection = cx_Oracle.connect(SampleEnv.EDITION_CONNECT_STRING)
editionConnectString = SampleEnv.GetEditionConnectString()
connection = cx_Oracle.connect(editionConnectString)
print("Edition should be None, actual value is:",
repr(connection.edition))
cursor = connection.cursor()
@ -38,8 +39,8 @@ print("Function should return 'Base Procedure', actually returns:",
repr(result))
# next, change the edition and recreate the procedure in the new edition
cursor.execute("alter session set edition = %s" % SampleEnv.EDITION_NAME)
print("Edition should be", repr(SampleEnv.EDITION_NAME.upper()),
cursor.execute("alter session set edition = %s" % SampleEnv.GetEditionName())
print("Edition should be", repr(SampleEnv.GetEditionName().upper()),
"actual value is:", repr(connection.edition))
cursor.execute("""
create or replace function TestEditions return varchar2 as
@ -58,17 +59,17 @@ print("Function should return 'Base Procedure', actually returns:",
repr(result))
# the edition can be set upon connection
connection = cx_Oracle.connect(SampleEnv.EDITION_CONNECT_STRING,
edition = SampleEnv.EDITION_NAME.upper())
connection = cx_Oracle.connect(editionConnectString,
edition = SampleEnv.GetEditionName().upper())
cursor = connection.cursor()
result = cursor.callfunc("TestEditions", str)
print("Function should return 'Edition 1 Procedure', actually returns:",
repr(result))
# it can also be set via the environment variable ORA_EDITION
os.environ["ORA_EDITION"] = SampleEnv.EDITION_NAME.upper()
connection = cx_Oracle.connect(SampleEnv.EDITION_CONNECT_STRING)
print("Edition should be", repr(SampleEnv.EDITION_NAME.upper()),
os.environ["ORA_EDITION"] = SampleEnv.GetEditionName().upper()
connection = cx_Oracle.connect(editionConnectString)
print("Edition should be", repr(SampleEnv.GetEditionName().upper()),
"actual value is:", repr(connection.edition))
cursor = connection.cursor()
result = cursor.callfunc("TestEditions", str)

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -35,7 +35,7 @@ class Cursor(cx_Oracle.Cursor):
# create new subclassed connection and cursor
connection = Connection(SampleEnv.MAIN_CONNECT_STRING)
connection = Connection(SampleEnv.GetMainConnectString())
cursor = connection.cursor()
# the names are now available directly for each query executed

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
@ -21,7 +21,7 @@ from __future__ import print_function
import cx_Oracle
import SampleEnv
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
cursor = connection.cursor()
# use PL/SQL block to return two cursors

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
@ -21,7 +21,7 @@ import cx_Oracle
import SampleEnv
# create and populate Oracle objects
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
typeObj = connection.gettype("MDSYS.SDO_GEOMETRY")
elementInfoTypeObj = connection.gettype("MDSYS.SDO_ELEM_INFO_ARRAY")
ordinateTypeObj = connection.gettype("MDSYS.SDO_ORDINATE_ARRAY")

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -18,7 +18,7 @@ from __future__ import print_function
import cx_Oracle
import SampleEnv
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
# create new empty object of the correct type
# note the use of a PL/SQL type defined in a package

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -13,7 +13,7 @@ from __future__ import print_function
import cx_Oracle
import SampleEnv
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
cursor = connection.cursor()
res = cursor.callfunc('myfunc', int, ('abc', 2))

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -14,7 +14,7 @@ from __future__ import print_function
import cx_Oracle
import SampleEnv
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
cursor = connection.cursor()
myvar = cursor.var(int)

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -17,7 +17,7 @@ import cx_Oracle
import SampleEnv
import datetime
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
# create new object of the correct type
# note the use of a PL/SQL record defined in a package

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -13,7 +13,7 @@ from __future__ import print_function
import cx_Oracle
import SampleEnv
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
sql = """
select * from SampleQueryTab

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -16,7 +16,7 @@ import time
import cx_Oracle
import SampleEnv
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
start = time.time()

View File

@ -1,31 +1,41 @@
This directory contains samples for cx_Oracle.
1. The schemas and SQL objects that are referenced in the samples can be
created by running the SQL script
[sql/SetupSamples.sql][1]. The
syntax is:
created by running the Python script [SetupSamples.py][1]. The script
requires SYSDBA privileges and will prompt for these credentials as well as
the names of the schemas and edition that will be created, unless a number
of environment variables are set as documented in the Python script
[SampleEnv.py][2]. Run the script using the following command:
sqlplus sys/syspassword@hostname/servicename as sysdba @sql/SetupSamples.sql
python SetupSamples.py
The script will create users `pythondemo` and `pythoneditions` and
will create an edition called `python_e1`.
Alternatively, the [SQL script][3] can be run directly via SQL\*Plus, which
will always prompt for the names of the schemas and edition that will be
created.
If you wish to change the names of the users or the name of the
edition you can edit the file [sql/SampleEnv.sql][2]. You will also
need to edit the file [SampleEnv.py][4] or set environment variables
as documented in it.
sqlplus sys/syspassword@hostname/servicename @sql/SetupSamples.sql
2. Run a Python script, for example:
python Query.py
3. After running cx_Oracle samples, the schemas and SQL objects can be
dropped by running the SQL script [sql/DropSamples.sql][3]. The
syntax is
dropped by running the Python script [DropSamples.py][4]. The script
requires SYSDBA privileges and will prompt for these credentials as well as
the names of the schemas and edition that will be dropped, unless a number
of environment variables are set as documented in the Python script
[SampleEnv.py][2]. Run the script using the following command:
sqlplus sys/syspassword@hostname/servicename as sysdba @sql/DropSamples.sql
python DropSamples.py
[1]: https://github.com/oracle/python-cx_Oracle/blob/master/samples/sql/SetupSamples.sql
[2]: https://github.com/oracle/python-cx_Oracle/blob/master/samples/sql/SampleEnv.sql
[3]: https://github.com/oracle/python-cx_Oracle/blob/master/samples/sql/DropSamples.sql
[4]: https://github.com/oracle/python-cx_Oracle/blob/master/samples/SampleEnv.py
Alternatively, the [SQL script][5] can be run directly via SQL\*Plus, which
will always prompt for the names of the schemas and edition that will be
dropped.
sqlplus sys/syspassword@hostname/servicename @sql/DropSamples.sql
[1]: https://github.com/oracle/python-cx_Oracle/blob/master/samples/SetupSamples.py
[2]: https://github.com/oracle/python-cx_Oracle/blob/master/samples/SampleEnv.py
[3]: https://github.com/oracle/python-cx_Oracle/blob/master/samples/sql/SetupSamples.sql
[4]: https://github.com/oracle/python-cx_Oracle/blob/master/samples/DropSamples.py
[5]: https://github.com/oracle/python-cx_Oracle/blob/master/samples/sql/DropSamples.sql

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -12,7 +12,7 @@ from __future__ import print_function
import cx_Oracle
import SampleEnv
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
cursor = connection.cursor()
refCursor = connection.cursor()

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
@ -29,7 +29,7 @@ def OutputTypeHandler(cursor, name, defaultType, size, precision, scale):
if defaultType == cx_Oracle.BLOB:
return cursor.var(cx_Oracle.LONG_BINARY, arraysize = cursor.arraysize)
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
connection.outputtypehandler = OutputTypeHandler
cursor = connection.cursor()

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -24,7 +24,7 @@ def OutputTypeHandler(cursor, name, defaultType, size, precision, scale):
if defaultType == cx_Oracle.NUMBER:
return cursor.var(decimal.Decimal, arraysize = cursor.arraysize)
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
connection.outputtypehandler = OutputTypeHandler
cursor = connection.cursor()
cursor.execute("select * from TestNumbers")

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
@ -12,7 +12,7 @@
# Returns all strings as unicode. This also demonstrates the use of an output
# type handler to change the way in which data is returned from a cursor.
#
# This script requires cx_Oracle 5.0 and higher.
# This script requires cx_Oracle 5.0 and higher and will only work in Python 2.
#------------------------------------------------------------------------------
from __future__ import print_function
@ -24,7 +24,7 @@ def OutputTypeHandler(cursor, name, defaultType, size, precision, scale):
if defaultType in (cx_Oracle.STRING, cx_Oracle.FIXED_CHAR):
return cursor.var(unicode, size, cursor.arraysize)
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
connection.outputtypehandler = OutputTypeHandler
cursor = connection.cursor()
cursor.execute("select * from TestStrings")

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
@ -28,7 +28,7 @@ class Test(object):
self.b = b
self.c = c
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
cursor = connection.cursor()
# change this to False if you want to create the table yourself using SQL*Plus

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -7,9 +7,8 @@
# applications should consider using External Authentication to
# avoid hard coded credentials.
#
# You can set values in environment variables to override the default values.
# If the default values are not going to be used, however, the SQL script
# sql/SampleEnv.sql will also need to be modified.
# You can set values in environment variables to bypass the sample requesting
# the information it requires.
#
# CX_ORACLE_SAMPLES_MAIN_USER: user used for most samples
# CX_ORACLE_SAMPLES_MAIN_PASSWORD: password of user used for most samples
@ -17,6 +16,8 @@
# CX_ORACLE_SAMPLES_EDITION_PASSWORD: password of user for editioning
# CX_ORACLE_SAMPLES_EDITION_NAME: name of edition for editioning
# CX_ORACLE_SAMPLES_CONNECT_STRING: connect string
# CX_ORACLE_SAMPLES_SYSDBA_USER: SYSDBA user for setting up samples
# CX_ORACLE_SAMPLES_SYSDBA_PASSWORD: SYSDBA password for setting up samples
#
# CX_ORACLE_SAMPLES_CONNECT_STRING can be set to an Easy Connect string, or a
# Net Service Name from a tnsnames.ora file or external naming service,
@ -36,33 +37,105 @@
# variable and put the file in $TNS_ADMIN/tnsnames.ora.
#------------------------------------------------------------------------------
from __future__ import print_function
import getpass
import os
import sys
# default values
DEFAULT_MAIN_USER = "pythondemo"
DEFAULT_MAIN_PASSWORD = "welcome"
DEFAULT_EDITION_USER = "pythoneditions"
DEFAULT_EDITION_PASSWORD = "welcome"
DEFAULT_EDITION_NAME = "python_e1"
DEFAULT_CONNECT_STRING = "localhost/orclpdb"
# values that will be used are the default values unless environment variables
# have been set as noted above
MAIN_USER = os.environ.get("CX_ORACLE_SAMPLES_MAIN_USER", DEFAULT_MAIN_USER)
MAIN_PASSWORD = os.environ.get("CX_ORACLE_SAMPLES_MAIN_PASSWORD",
DEFAULT_MAIN_PASSWORD)
EDITION_USER = os.environ.get("CX_ORACLE_SAMPLES_EDITION_USER",
DEFAULT_EDITION_USER)
EDITION_PASSWORD = os.environ.get("CX_ORACLE_SAMPLES_EDITION_PASSWORD",
DEFAULT_EDITION_PASSWORD)
EDITION_NAME = os.environ.get("CX_ORACLE_SAMPLES_EDITION_NAME",
DEFAULT_EDITION_NAME)
CONNECT_STRING = os.environ.get("CX_ORACLE_SAMPLES_CONNECT_STRING",
DEFAULT_CONNECT_STRING)
# dictionary containing all parameters; these are acquired as needed by the
# methods below (which should be used instead of consulting this dictionary
# directly) and then stored so that a value is not requested more than once
PARAMETERS = {}
# calculated values based on the values above
MAIN_CONNECT_STRING = "%s/%s@%s" % (MAIN_USER, MAIN_PASSWORD, CONNECT_STRING)
EDITION_CONNECT_STRING = "%s/%s@%s" % \
(EDITION_USER, EDITION_PASSWORD, CONNECT_STRING)
DRCP_CONNECT_STRING = MAIN_CONNECT_STRING + ":pooled"
def GetValue(name, label, defaultValue=""):
value = PARAMETERS.get(name)
if value is not None:
return value
envName = "CX_ORACLE_SAMPLES_" + name
value = os.environ.get(envName)
if value is None:
if defaultValue:
label += " [%s]" % defaultValue
label += ": "
if defaultValue:
value = input(label).strip()
else:
value = getpass.getpass(label)
if not value:
value = defaultValue
return value
def GetMainUser():
return GetValue("MAIN_USER", "Main User Name", DEFAULT_MAIN_USER)
def GetMainPassword():
return GetValue("MAIN_PASSWORD", "Password for %s" % GetMainUser())
def GetEditionUser():
return GetValue("EDITION_USER", "Edition User Name", DEFAULT_EDITION_USER)
def GetEditionPassword():
return GetValue("EDITION_PASSWORD", "Password for %s" % GetEditionUser())
def GetEditionName():
return GetValue("EDITION_NAME", "Edition Name", DEFAULT_EDITION_NAME)
def GetConnectString():
return GetValue("CONNECT_STRING", "Connect String", DEFAULT_CONNECT_STRING)
def GetMainConnectString(password=None):
if password is None:
password = GetMainPassword()
return "%s/%s@%s" % (GetMainUser(), password, GetConnectString())
def GetDrcpConnectString():
return GetMainConnectString() + ":pooled"
def GetEditionConnectString():
return "%s/%s@%s" % \
(GetEditionUser(), GetEditionPassword(), GetConnectString())
def GetSysdbaConnectString():
sysdbaUser = GetValue("SYSDBA_USER", "SYSDBA user", "sys")
sysdbaPassword = GetValue("SYSDBA_PASSWORD",
"Password for %s" % sysdbaUser)
return "%s/%s@%s" % (sysdbaUser, sysdbaPassword, GetConnectString())
def RunSqlScript(conn, scriptName, **kwargs):
statementParts = []
cursor = conn.cursor()
replaceValues = [("&" + k + ".", v) for k, v in kwargs.items()] + \
[("&" + k, v) for k, v in kwargs.items()]
scriptDir = os.path.dirname(os.path.abspath(sys.argv[0]))
fileName = os.path.join(scriptDir, "sql", scriptName + "Exec.sql")
for line in open(fileName):
if line.strip() == "/":
statement = "".join(statementParts).strip()
if statement:
for searchValue, replaceValue in replaceValues:
statement = statement.replace(searchValue, replaceValue)
cursor.execute(statement)
statementParts = []
else:
statementParts.append(line)
cursor.execute("""
select name, type, line, position, text
from dba_errors
where owner = upper(:owner)
order by name, type, line, position""",
owner = GetMainUser())
prevName = prevObjType = None
for name, objType, lineNum, position, text in cursor:
if name != prevName or objType != prevObjType:
print("%s (%s)" % (name, objType))
prevName = name
prevObjType = objType
print(" %s/%s %s" % (lineNum, position, text))

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
@ -21,7 +21,7 @@ from __future__ import print_function
import cx_Oracle
import SampleEnv
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
# show all of the rows available in the table
cursor = connection.cursor()

View File

@ -39,10 +39,10 @@ SUPPORTED_KEYS = {
}
# define session callback
def init_session(conn, requestedTag):
def InitSession(conn, requestedTag):
# display the requested and actual tags
print("init_session(): requested tag=%r, actual tag=%r" % \
print("InitSession(): requested tag=%r, actual tag=%r" % \
(requestedTag, conn.tag))
# tags are expected to be in the form "key1=value1;key2=value2"
@ -75,9 +75,9 @@ def init_session(conn, requestedTag):
# create pool with session callback defined
pool = cx_Oracle.SessionPool(SampleEnv.MAIN_USER, SampleEnv.MAIN_PASSWORD,
SampleEnv.CONNECT_STRING, min=2, max=5, increment=1, threaded=True,
sessionCallback=init_session)
pool = cx_Oracle.SessionPool(SampleEnv.GetMainUser(),
SampleEnv.GetMainPassword(), SampleEnv.GetConnectString(), min=2,
max=5, increment=1, threaded=True, sessionCallback=InitSession)
# acquire session without specifying a tag; since the session returned is
# newly created, the callback will be invoked but since there is no tag

View File

@ -24,8 +24,9 @@ import cx_Oracle
import SampleEnv
# create pool with session callback defined
pool = cx_Oracle.SessionPool(SampleEnv.MAIN_USER, SampleEnv.MAIN_PASSWORD,
SampleEnv.CONNECT_STRING, min=2, max=5, increment=1, threaded=True,
pool = cx_Oracle.SessionPool(SampleEnv.GetMainUser(),
SampleEnv.GetMainPassword(), SampleEnv.GetConnectString(), min=2,
max=5, increment=1, threaded=True,
sessionCallback="pkg_SessionCallback.TheCallback")
# truncate table logging calls to PL/SQL session callback

36
samples/SetupSamples.py Normal file
View File

@ -0,0 +1,36 @@
#------------------------------------------------------------------------------
# Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
# SetupSamples.py
#
# Creates users and populates their schemas with the tables and packages
# necessary for the cx_Oracle samples. An edition is also created for the
# demonstration of PL/SQL editioning.
#------------------------------------------------------------------------------
from __future__ import print_function
import cx_Oracle
import SampleEnv
import DropSamples
# connect as SYSDBA
conn = cx_Oracle.connect(SampleEnv.GetSysdbaConnectString(),
mode = cx_Oracle.SYSDBA)
# drop existing users and editions, if applicable
DropSamples.DropSamples(conn)
# create sample schema and edition
print("Creating sample schemas and edition...")
SampleEnv.RunSqlScript(conn, "SetupSamples",
main_user = SampleEnv.GetMainUser(),
main_password = SampleEnv.GetMainPassword(),
edition_user = SampleEnv.GetEditionUser(),
edition_password = SampleEnv.GetEditionPassword(),
edition_name = SampleEnv.GetEditionName())
print("Done.")

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -17,7 +17,7 @@ from __future__ import print_function
import cx_Oracle
import SampleEnv
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
# The general recommendation for simple SODA usage is to enable autocommit
connection.autocommit = True

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -30,7 +30,7 @@ from shapely.wkb import loads
import geopandas as gpd
# create Oracle connection and cursor objects
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
cursor = connection.cursor()
# enable autocommit to avoid the additional round trip to the database to

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -21,7 +21,7 @@ import SampleEnv
class Connection(cx_Oracle.Connection):
def __init__(self):
connectString = SampleEnv.MAIN_CONNECT_STRING
connectString = SampleEnv.GetMainConnectString()
print("CONNECT to database")
return super(Connection, self).__init__(connectString)

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2017, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------
#------------------------------------------------------------------------------
@ -19,8 +19,9 @@ import cx_Oracle
import SampleEnv
import threading
pool = cx_Oracle.SessionPool(SampleEnv.MAIN_USER, SampleEnv.MAIN_PASSWORD,
SampleEnv.CONNECT_STRING, 2, 5, 1, threaded = True)
pool = cx_Oracle.SessionPool(SampleEnv.GetMainUser(),
SampleEnv.GetMainPassword(), SampleEnv.GetConnectString(), min=2,
max=5, increment=1, threaded=True)
def TheLongQuery():
conn = pool.acquire()

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
@ -40,9 +40,6 @@ import SampleEnv
import sys
# constants
SESSION_MIN = 1
SESSION_MAX = 9
SESSION_INCR = 2
CONNECT_STRING = "localhost/orcl-tg"
# for Python 2.7 we need raw_input
@ -52,8 +49,9 @@ except NameError:
pass
# create transaction and generate a recoverable error
pool = cx_Oracle.SessionPool(SampleEnv.MAIN_USER, SampleEnv.MAIN_PASSWORD,
CONNECT_STRING, SESSION_MIN, SESSION_MAX, SESSION_INCR)
pool = cx_Oracle.SessionPool(SampleEnv.GetMainUser(),
SampleEnv.GetMainPassword(), CONNECT_STRING, min=1,
max=9, increment=2)
connection = pool.acquire()
cursor = connection.cursor()
cursor.execute("""
@ -63,7 +61,7 @@ cursor.execute("""
insert into TestTempTable
values (1, null)""")
input("Please kill %s session now. Press ENTER when complete." % \
SampleEnv.MAIN_USER)
SampleEnv.GetMainUser())
try:
connection.commit() # this should fail
sys.exit("Session was not killed. Terminating.")

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
@ -24,7 +24,7 @@ import cx_Oracle
import datetime
import SampleEnv
con = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
con = cx_Oracle.connect(SampleEnv.GetMainConnectString())
objType = con.gettype("UDT_BUILDING")
class Building(object):

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------
# Copyright (c) 2017, 2018, Oracle and/or its affiliates. All rights reserved.
# Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved.
#
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
#
@ -28,7 +28,7 @@ DATA = [
]
# truncate table so sample can be rerun
connection = cx_Oracle.connect(SampleEnv.MAIN_CONNECT_STRING)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString())
cursor = connection.cursor()
print("Truncating table...")
cursor.execute("truncate table TestUniversalRowids")

View File

@ -1,5 +1,5 @@
/*-----------------------------------------------------------------------------
* Copyright 2017, Oracle and/or its affiliates. All rights reserved.
* Copyright 2017, 2019, Oracle and/or its affiliates. All rights reserved.
*---------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------
@ -7,35 +7,23 @@
* Drops database objects used for cx_Oracle samples.
*
* Run this like:
* sqlplus / as sysdba @DropSamples
*
* Note that the script SampleEnv.sql should be modified if you would like to
* use something other than the default schemas and passwords.
* sqlplus sys/syspassword@hostname/servicename as sysdba @DropSamples
*---------------------------------------------------------------------------*/
whenever sqlerror exit failure
-- setup environment
@@SampleEnv.sql
-- get parameters
set echo off termout on feedback off verify off
accept main_user char default pythondemo -
prompt "Name of main schema [pythondemo]: "
accept edition_user char default pythoneditions -
prompt "Name of edition schema [pythoneditions]: "
accept edition_name char default python_e1 -
prompt "Name of edition [python_e1]: "
set feedback on
begin
-- perform work
@@DropSamplesExec.sql
for r in
( select username
from dba_users
where username in (upper('&main_user'), upper('&edition_user'))
) loop
execute immediate 'drop user ' || r.username || ' cascade';
end loop;
for r in
( select edition_name
from dba_editions
where edition_name in (upper('&edition_name'))
) loop
execute immediate 'drop edition ' || r.edition_name || ' cascade';
end loop;
end;
/
exit

View File

@ -0,0 +1,33 @@
/*-----------------------------------------------------------------------------
* Copyright 2017, 2019, Oracle and/or its affiliates. All rights reserved.
*---------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------
* DropSamplesExec.sql
* This script performs the actual work of dropping the database schemas and
* edition used by the cx_Oracle samples. It is called by the DropSamples.sql
* and SetupSamples.sql files after acquiring the necessary parameters and
* also by the Python script DropSamples.py.
*---------------------------------------------------------------------------*/
begin
for r in
( select username
from dba_users
where username in (upper('&main_user'), upper('&edition_user'))
) loop
execute immediate 'drop user ' || r.username || ' cascade';
end loop;
for r in
( select edition_name
from dba_editions
where edition_name in (upper('&edition_name'))
) loop
execute immediate 'drop edition ' || r.edition_name || ' cascade';
end loop;
end;
/

View File

@ -1,31 +0,0 @@
/*-----------------------------------------------------------------------------
* Copyright 2017, Oracle and/or its affiliates. All rights reserved.
*---------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------
* SampleEnv.sql
* Sets up configuration for the SetupSamples.sql and DropSamples.sql
* scripts. Change the values below if you would like to use something other
* than the default values. Note that the environment variables noted below
* will also need to be set, or the Python script SampleEnv.py will need to be
* changed if non-default values are used.
*---------------------------------------------------------------------------*/
set echo off termout on feedback off verify off
define main_user = "pythondemo" -- $CX_ORACLE_SAMPLES_MAIN_USER
define main_password = "welcome" -- $CX_ORACLE_SAMPLES_MAIN_PASSWORD
define edition_user = "pythoneditions" -- $CX_ORACLE_SAMPLES_EDITION_USER
define edition_password = "welcome" -- $CX_ORACLE_SAMPLES_EDITION_PASSWORD
define edition_name = "python_e1" -- $CX_ORACLE_SAMPLES_EDITION_NAME
prompt ************************************************************************
prompt CONFIGURATION
prompt ************************************************************************
prompt Main Schema: &main_user
prompt Edition Schema: &edition_user
prompt Edition Name: &edition_name
prompt
set echo on verify on feedback on

View File

@ -1,473 +1,34 @@
/*-----------------------------------------------------------------------------
* Copyright 2017, 2018, Oracle and/or its affiliates. All rights reserved.
* Copyright 2017, 2019, Oracle and/or its affiliates. All rights reserved.
*---------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------
* SetupSamples.sql
* Creates users and populates their schemas with the tables and packages
* necessary for the cx_Oracle samples. An edition is also created for the
* demonstration of PL/SQL editioning.
* Creates and populates schemas with the database objects used by the
* cx_Oracle samples. An edition is also created for the demonstration of
* PL/SQL editioning.
*
* Run this like:
* sqlplus / as sysdba @SetupSamples
*
* Note that the script SampleEnv.sql should be modified if you would like to
* use something other than the default configuration.
* sqlplus sys/syspassword@hostname/servicename as sysdba @SetupSamples
*---------------------------------------------------------------------------*/
whenever sqlerror exit failure
-- drop existing users and edition, if applicable
@@DropSamples.sql
alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS';
alter session set nls_numeric_characters='.,';
create user &main_user identified by &main_password
quota unlimited on users
default tablespace users;
grant
create session,
create table,
create procedure,
create type,
select any dictionary,
change notification
to &main_user;
grant execute on dbms_aqadm to &main_user;
grant execute on dbms_lock to &main_user;
begin
for r in
( select role
from dba_roles
where role in ('SODA_APP')
) loop
execute immediate 'grant ' || r.role || ' to &main_user';
end loop;
end;
/
create user &edition_user identified by &edition_password;
grant
create session,
create procedure
to &edition_user;
alter user &edition_user enable editions;
create edition &edition_name;
grant use on edition &edition_name to &edition_user;
-- create types
create type &main_user..udt_SubObject as object (
SubNumberValue number,
SubStringValue varchar2(60)
);
/
create or replace type &main_user..udt_Building as object (
BuildingId number(9),
NumFloors number(3),
Description varchar2(60),
DateBuilt date
);
/
create or replace type &main_user..udt_Book as object (
Title varchar2(100),
Authors varchar2(100),
Price number(5,2)
);
/
-- create tables
create table &main_user..TestNumbers (
IntCol number(9) not null,
NumberCol number(9, 2) not null,
FloatCol float not null,
UnconstrainedCol number not null,
NullableCol number(38)
);
create table &main_user..TestStrings (
IntCol number(9) not null,
StringCol varchar2(20) not null,
RawCol raw(30) not null,
FixedCharCol char(40) not null,
NullableCol varchar2(50)
);
create table &main_user..TestCLOBs (
IntCol number(9) not null,
CLOBCol clob not null
);
create table &main_user..TestBLOBs (
IntCol number(9) not null,
BLOBCol blob not null
);
create table &main_user..TestTempTable (
IntCol number(9) not null,
StringCol varchar2(400),
constraint TestTempTable_pk primary key (IntCol)
);
create table &main_user..TestUniversalRowids (
IntCol number(9) not null,
StringCol varchar2(250) not null,
DateCol date not null,
constraint TestUniversalRowids_pk primary key (IntCol, StringCol, DateCol)
) organization index;
create table &main_user..TestBuildings (
BuildingId number(9) not null,
BuildingObj &main_user..udt_Building not null
);
create table &main_user..BigTab (
mycol varchar2(20)
);
create table &main_user..SampleQueryTab (
id number not null,
name varchar2(20) not null
);
create table &main_user..MyTab (
id number,
data varchar2(20)
);
create table &main_user..ParentTable (
ParentId number(9) not null,
Description varchar2(60) not null,
constraint ParentTable_pk primary key (ParentId)
);
create table &main_user..ChildTable (
ChildId number(9) not null,
ParentId number(9) not null,
Description varchar2(60) not null,
constraint ChildTable_pk primary key (ChildId),
constraint ChildTable_fk foreign key (ParentId) references &main_user..ParentTable
);
create table &main_user..Ptab (
myid number,
mydata varchar(20)
);
create table &main_user..PlsqlSessionCallbacks (
RequestedTag varchar2(250),
ActualTag varchar2(250),
FixupTimestamp timestamp
);
-- create queue table and queues for demonstrating advanced queuing
begin
dbms_aqadm.create_queue_table('&main_user..BOOK_QUEUE',
'&main_user..UDT_BOOK');
dbms_aqadm.create_queue('&main_user..BOOKS', '&main_user..BOOK_QUEUE');
dbms_aqadm.start_queue('&main_user..BOOKS');
end;
/
-- populate tables
begin
for i in 1..20000
loop
insert into &main_user..BigTab (mycol) values (dbms_random.string('A',20));
end loop;
end;
/
begin
for i in 1..10 loop
insert into &main_user..TestNumbers
values (i, i + i * 0.25, i + i * .75, i * i * i + i *.5,
decode(mod(i, 2), 0, null, power(143, i)));
end loop;
end;
/
declare
t_RawValue raw(30);
function ConvertHexDigit(a_Value number) return varchar2 is
begin
if a_Value between 0 and 9 then
return to_char(a_Value);
end if;
return chr(ascii('A') + a_Value - 10);
end;
function ConvertToHex(a_Value varchar2) return varchar2 is
t_HexValue varchar2(60);
t_Digit number;
begin
for i in 1..length(a_Value) loop
t_Digit := ascii(substr(a_Value, i, 1));
t_HexValue := t_HexValue ||
ConvertHexDigit(trunc(t_Digit / 16)) ||
ConvertHexDigit(mod(t_Digit, 16));
end loop;
return t_HexValue;
end;
begin
for i in 1..10 loop
t_RawValue := hextoraw(ConvertToHex('Raw ' || to_char(i)));
insert into &main_user..TestStrings
values (i, 'String ' || to_char(i), t_RawValue,
'Fixed Char ' || to_char(i),
decode(mod(i, 2), 0, null, 'Nullable ' || to_char(i)));
end loop;
end;
/
insert into &main_user..ParentTable values (10, 'Parent 10');
insert into &main_user..ParentTable values (20, 'Parent 20');
insert into &main_user..ParentTable values (30, 'Parent 30');
insert into &main_user..ParentTable values (40, 'Parent 40');
insert into &main_user..ParentTable values (50, 'Parent 50');
insert into &main_user..ChildTable values (1001, 10, 'Child A of Parent 10');
insert into &main_user..ChildTable values (1002, 20, 'Child A of Parent 20');
insert into &main_user..ChildTable values (1003, 20, 'Child B of Parent 20');
insert into &main_user..ChildTable values (1004, 20, 'Child C of Parent 20');
insert into &main_user..ChildTable values (1005, 30, 'Child A of Parent 30');
insert into &main_user..ChildTable values (1006, 30, 'Child B of Parent 30');
insert into &main_user..ChildTable values (1007, 40, 'Child A of Parent 40');
insert into &main_user..ChildTable values (1008, 40, 'Child B of Parent 40');
insert into &main_user..ChildTable values (1009, 40, 'Child C of Parent 40');
insert into &main_user..ChildTable values (1010, 40, 'Child D of Parent 40');
insert into &main_user..ChildTable values (1011, 40, 'Child E of Parent 40');
insert into &main_user..ChildTable values (1012, 50, 'Child A of Parent 50');
insert into &main_user..ChildTable values (1013, 50, 'Child B of Parent 50');
insert into &main_user..ChildTable values (1014, 50, 'Child C of Parent 50');
insert into &main_user..ChildTable values (1015, 50, 'Child D of Parent 50');
insert into &main_user..SampleQueryTab values (1, 'Anthony');
insert into &main_user..SampleQueryTab values (2, 'Barbie');
insert into &main_user..SampleQueryTab values (3, 'Chris');
insert into &main_user..SampleQueryTab values (4, 'Dazza');
insert into &main_user..SampleQueryTab values (5, 'Erin');
insert into &main_user..SampleQueryTab values (6, 'Frankie');
insert into &main_user..SampleQueryTab values (7, 'Gerri');
commit;
--
-- For PL/SQL Examples
--
create or replace function &main_user..myfunc (
a_Data varchar2,
a_Id number
) return number as
begin
insert into &main_user..ptab (mydata, myid) values (a_Data, a_Id);
return (a_Id * 2);
end;
/
create or replace procedure &main_user..myproc (
a_Value1 number,
a_Value2 out number
) as
begin
a_Value2 := a_Value1 * 2;
end;
/
create or replace procedure &main_user..myrefcursorproc (
a_StartingValue number,
a_EndingValue number,
a_RefCursor out sys_refcursor
) as
begin
open a_RefCursor for
select *
from TestStrings
where IntCol between a_StartingValue and a_EndingValue;
end;
/
--
-- Create package for demoing PL/SQL collections and records.
--
create or replace package &main_user..pkg_Demo as
type udt_StringList is table of varchar2(100) index by binary_integer;
type udt_DemoRecord is record (
NumberValue number,
StringValue varchar2(30),
DateValue date,
BooleanValue boolean
);
procedure DemoCollectionOut (
a_Value out nocopy udt_StringList
);
procedure DemoRecordsInOut (
a_Value in out nocopy udt_DemoRecord
);
end;
/
create or replace package body &main_user..pkg_Demo as
procedure DemoCollectionOut (
a_Value out nocopy udt_StringList
) is
begin
a_Value(-1048576) := 'First element';
a_Value(-576) := 'Second element';
a_Value(284) := 'Third element';
a_Value(8388608) := 'Fourth element';
end;
procedure DemoRecordsInOut (
a_Value in out nocopy udt_DemoRecord
) is
begin
a_Value.NumberValue := a_Value.NumberValue * 2;
a_Value.StringValue := a_Value.StringValue || ' (Modified)';
a_Value.DateValue := a_Value.DateValue + 5;
a_Value.BooleanValue := not a_Value.BooleanValue;
end;
end;
/
--
-- Create package for demoing PL/SQL session callback
--
create or replace package &main_user..pkg_SessionCallback as
procedure TheCallback (
a_RequestedTag varchar2,
a_ActualTag varchar2
);
end;
/
create or replace package body &main_user..pkg_SessionCallback as
type udt_Properties is table of varchar2(64) index by varchar2(64);
procedure LogCall (
a_RequestedTag varchar2,
a_ActualTag varchar2
) is
pragma autonomous_transaction;
begin
insert into PlsqlSessionCallbacks
values (a_RequestedTag, a_ActualTag, systimestamp);
commit;
end;
procedure ParseProperty (
a_Property varchar2,
a_Name out nocopy varchar2,
a_Value out nocopy varchar2
) is
t_Pos number;
begin
t_Pos := instr(a_Property, '=');
if t_Pos = 0 then
raise_application_error(-20000, 'Tag must contain key=value pairs');
end if;
a_Name := substr(a_Property, 1, t_Pos - 1);
a_Value := substr(a_Property, t_Pos + 1);
end;
procedure SetProperty (
a_Name varchar2,
a_Value varchar2
) is
t_ValidValues udt_Properties;
begin
if a_Name = 'TIME_ZONE' then
t_ValidValues('UTC') := 'UTC';
t_ValidValues('MST') := '-07:00';
elsif a_Name = 'NLS_DATE_FORMAT' then
t_ValidValues('SIMPLE') := 'YYYY-MM-DD HH24:MI';
t_ValidValues('FULL') := 'YYYY-MM-DD HH24:MI:SS';
else
raise_application_error(-20000, 'Unsupported session setting');
end if;
if not t_ValidValues.exists(a_Value) then
raise_application_error(-20000, 'Unsupported session setting');
end if;
execute immediate
'ALTER SESSION SET ' || a_Name || '=''' ||
t_ValidValues(a_Value) || '''';
end;
procedure ParseTag (
a_Tag varchar2,
a_Properties out nocopy udt_Properties
) is
t_PropertyName varchar2(64);
t_PropertyValue varchar2(64);
t_StartPos number;
t_EndPos number;
begin
t_StartPos := 1;
while t_StartPos < length(a_Tag) loop
t_EndPos := instr(a_Tag, ';', t_StartPos);
if t_EndPos = 0 then
t_EndPos := length(a_Tag) + 1;
end if;
ParseProperty(substr(a_Tag, t_StartPos, t_EndPos - t_StartPos),
t_PropertyName, t_PropertyValue);
a_Properties(t_PropertyName) := t_PropertyValue;
t_StartPos := t_EndPos + 1;
end loop;
end;
procedure TheCallback (
a_RequestedTag varchar2,
a_ActualTag varchar2
) is
t_RequestedProps udt_Properties;
t_ActualProps udt_Properties;
t_PropertyName varchar2(64);
begin
LogCall(a_RequestedTag, a_ActualTag);
ParseTag(a_RequestedTag, t_RequestedProps);
ParseTag(a_ActualTag, t_ActualProps);
t_PropertyName := t_RequestedProps.first;
while t_PropertyName is not null loop
if not t_ActualProps.exists(t_PropertyName) or
t_ActualProps(t_PropertyName) !=
t_RequestedProps(t_PropertyName) then
SetProperty(t_PropertyName, t_RequestedProps(t_PropertyName));
end if;
t_PropertyName := t_RequestedProps.next(t_PropertyName);
end loop;
end;
end;
/
-- get parameters
set echo off termout on feedback off verify off
accept main_user char default pythondemo -
prompt "Name of main schema [pythondemo]: "
accept main_password char prompt "Password for &main_user: " HIDE
accept edition_user char default pythoneditions -
prompt "Name of edition schema [pythoneditions]: "
accept edition_password char prompt "Password for &edition_user: " HIDE
accept edition_name char default python_e1 -
prompt "Name of edition [python_e1]: "
set feedback on
-- perform work
@@DropSamplesExec.sql
@@SetupSamplesExec.sql
exit

View File

@ -0,0 +1,518 @@
/*-----------------------------------------------------------------------------
* Copyright 2017, 2019, Oracle and/or its affiliates. All rights reserved.
*---------------------------------------------------------------------------*/
/*-----------------------------------------------------------------------------
* SetupSamplesExec.sql
* This script performs the actual work of creating and populating the
* schemas with the database objects used by the cx_Oracle samples. An edition
* is also created for the demonstration of PL/SQL editioning. It is called by
* the SetupSamples.sql file after acquiring the necessary parameters and also
* by the Python script SetupSamples.py.
*---------------------------------------------------------------------------*/
alter session set nls_date_format = 'YYYY-MM-DD HH24:MI:SS'
/
alter session set nls_numeric_characters='.,'
/
create user &main_user identified by &main_password
quota unlimited on users
default tablespace users
/
grant
create session,
create table,
create procedure,
create type,
select any dictionary,
change notification
to &main_user
/
grant execute on dbms_aqadm to &main_user
/
grant execute on dbms_lock to &main_user
/
begin
for r in
( select role
from dba_roles
where role in ('SODA_APP')
) loop
execute immediate 'grant ' || r.role || ' to &main_user';
end loop;
end;
/
create user &edition_user identified by &edition_password
/
grant
create session,
create procedure
to &edition_user
/
alter user &edition_user enable editions
/
create edition &edition_name
/
grant use on edition &edition_name to &edition_user
/
-- create types
create type &main_user..udt_SubObject as object (
SubNumberValue number,
SubStringValue varchar2(60)
);
/
create or replace type &main_user..udt_Building as object (
BuildingId number(9),
NumFloors number(3),
Description varchar2(60),
DateBuilt date
);
/
create or replace type &main_user..udt_Book as object (
Title varchar2(100),
Authors varchar2(100),
Price number(5,2)
);
/
-- create tables
create table &main_user..TestNumbers (
IntCol number(9) not null,
NumberCol number(9, 2) not null,
FloatCol float not null,
UnconstrainedCol number not null,
NullableCol number(38)
)
/
create table &main_user..TestStrings (
IntCol number(9) not null,
StringCol varchar2(20) not null,
RawCol raw(30) not null,
FixedCharCol char(40) not null,
NullableCol varchar2(50)
)
/
create table &main_user..TestCLOBs (
IntCol number(9) not null,
CLOBCol clob not null
)
/
create table &main_user..TestBLOBs (
IntCol number(9) not null,
BLOBCol blob not null
)
/
create table &main_user..TestTempTable (
IntCol number(9) not null,
StringCol varchar2(400),
constraint TestTempTable_pk primary key (IntCol)
)
/
create table &main_user..TestUniversalRowids (
IntCol number(9) not null,
StringCol varchar2(250) not null,
DateCol date not null,
constraint TestUniversalRowids_pk primary key (IntCol, StringCol, DateCol)
) organization index
/
create table &main_user..TestBuildings (
BuildingId number(9) not null,
BuildingObj &main_user..udt_Building not null
)
/
create table &main_user..BigTab (
mycol varchar2(20)
)
/
create table &main_user..SampleQueryTab (
id number not null,
name varchar2(20) not null
)
/
create table &main_user..MyTab (
id number,
data varchar2(20)
)
/
create table &main_user..ParentTable (
ParentId number(9) not null,
Description varchar2(60) not null,
constraint ParentTable_pk primary key (ParentId)
)
/
create table &main_user..ChildTable (
ChildId number(9) not null,
ParentId number(9) not null,
Description varchar2(60) not null,
constraint ChildTable_pk primary key (ChildId),
constraint ChildTable_fk foreign key (ParentId)
references &main_user..ParentTable
)
/
create table &main_user..Ptab (
myid number,
mydata varchar(20)
)
/
create table &main_user..PlsqlSessionCallbacks (
RequestedTag varchar2(250),
ActualTag varchar2(250),
FixupTimestamp timestamp
)
/
-- create queue table and queues for demonstrating advanced queuing
begin
dbms_aqadm.create_queue_table('&main_user..BOOK_QUEUE',
'&main_user..UDT_BOOK');
dbms_aqadm.create_queue('&main_user..BOOKS', '&main_user..BOOK_QUEUE');
dbms_aqadm.start_queue('&main_user..BOOKS');
end;
/
-- populate tables
begin
for i in 1..20000 loop
insert into &main_user..BigTab (mycol)
values (dbms_random.string('A', 20));
end loop;
end;
/
begin
for i in 1..10 loop
insert into &main_user..TestNumbers
values (i, i + i * 0.25, i + i * .75, i * i * i + i *.5,
decode(mod(i, 2), 0, null, power(143, i)));
end loop;
end;
/
declare
t_RawValue raw(30);
function ConvertHexDigit(a_Value number) return varchar2 is
begin
if a_Value between 0 and 9 then
return to_char(a_Value);
end if;
return chr(ascii('A') + a_Value - 10);
end;
function ConvertToHex(a_Value varchar2) return varchar2 is
t_HexValue varchar2(60);
t_Digit number;
begin
for i in 1..length(a_Value) loop
t_Digit := ascii(substr(a_Value, i, 1));
t_HexValue := t_HexValue ||
ConvertHexDigit(trunc(t_Digit / 16)) ||
ConvertHexDigit(mod(t_Digit, 16));
end loop;
return t_HexValue;
end;
begin
for i in 1..10 loop
t_RawValue := hextoraw(ConvertToHex('Raw ' || to_char(i)));
insert into &main_user..TestStrings
values (i, 'String ' || to_char(i), t_RawValue,
'Fixed Char ' || to_char(i),
decode(mod(i, 2), 0, null, 'Nullable ' || to_char(i)));
end loop;
end;
/
insert into &main_user..ParentTable values (10, 'Parent 10')
/
insert into &main_user..ParentTable values (20, 'Parent 20')
/
insert into &main_user..ParentTable values (30, 'Parent 30')
/
insert into &main_user..ParentTable values (40, 'Parent 40')
/
insert into &main_user..ParentTable values (50, 'Parent 50')
/
insert into &main_user..ChildTable values (1001, 10, 'Child A of Parent 10')
/
insert into &main_user..ChildTable values (1002, 20, 'Child A of Parent 20')
/
insert into &main_user..ChildTable values (1003, 20, 'Child B of Parent 20')
/
insert into &main_user..ChildTable values (1004, 20, 'Child C of Parent 20')
/
insert into &main_user..ChildTable values (1005, 30, 'Child A of Parent 30')
/
insert into &main_user..ChildTable values (1006, 30, 'Child B of Parent 30')
/
insert into &main_user..ChildTable values (1007, 40, 'Child A of Parent 40')
/
insert into &main_user..ChildTable values (1008, 40, 'Child B of Parent 40')
/
insert into &main_user..ChildTable values (1009, 40, 'Child C of Parent 40')
/
insert into &main_user..ChildTable values (1010, 40, 'Child D of Parent 40')
/
insert into &main_user..ChildTable values (1011, 40, 'Child E of Parent 40')
/
insert into &main_user..ChildTable values (1012, 50, 'Child A of Parent 50')
/
insert into &main_user..ChildTable values (1013, 50, 'Child B of Parent 50')
/
insert into &main_user..ChildTable values (1014, 50, 'Child C of Parent 50')
/
insert into &main_user..ChildTable values (1015, 50, 'Child D of Parent 50')
/
insert into &main_user..SampleQueryTab values (1, 'Anthony')
/
insert into &main_user..SampleQueryTab values (2, 'Barbie')
/
insert into &main_user..SampleQueryTab values (3, 'Chris')
/
insert into &main_user..SampleQueryTab values (4, 'Dazza')
/
insert into &main_user..SampleQueryTab values (5, 'Erin')
/
insert into &main_user..SampleQueryTab values (6, 'Frankie')
/
insert into &main_user..SampleQueryTab values (7, 'Gerri')
/
commit
/
--
-- For PL/SQL Examples
--
create or replace function &main_user..myfunc (
a_Data varchar2,
a_Id number
) return number as
begin
insert into &main_user..ptab (mydata, myid) values (a_Data, a_Id);
return (a_Id * 2);
end;
/
create or replace procedure &main_user..myproc (
a_Value1 number,
a_Value2 out number
) as
begin
a_Value2 := a_Value1 * 2;
end;
/
create or replace procedure &main_user..myrefcursorproc (
a_StartingValue number,
a_EndingValue number,
a_RefCursor out sys_refcursor
) as
begin
open a_RefCursor for
select *
from TestStrings
where IntCol between a_StartingValue and a_EndingValue;
end;
/
--
-- Create package for demoing PL/SQL collections and records.
--
create or replace package &main_user..pkg_Demo as
type udt_StringList is table of varchar2(100) index by binary_integer;
type udt_DemoRecord is record (
NumberValue number,
StringValue varchar2(30),
DateValue date,
BooleanValue boolean
);
procedure DemoCollectionOut (
a_Value out nocopy udt_StringList
);
procedure DemoRecordsInOut (
a_Value in out nocopy udt_DemoRecord
);
end;
/
create or replace package body &main_user..pkg_Demo as
procedure DemoCollectionOut (
a_Value out nocopy udt_StringList
) is
begin
a_Value(-1048576) := 'First element';
a_Value(-576) := 'Second element';
a_Value(284) := 'Third element';
a_Value(8388608) := 'Fourth element';
end;
procedure DemoRecordsInOut (
a_Value in out nocopy udt_DemoRecord
) is
begin
a_Value.NumberValue := a_Value.NumberValue * 2;
a_Value.StringValue := a_Value.StringValue || ' (Modified)';
a_Value.DateValue := a_Value.DateValue + 5;
a_Value.BooleanValue := not a_Value.BooleanValue;
end;
end;
/
--
-- Create package for demoing PL/SQL session callback
--
create or replace package &main_user..pkg_SessionCallback as
procedure TheCallback (
a_RequestedTag varchar2,
a_ActualTag varchar2
);
end;
/
create or replace package body &main_user..pkg_SessionCallback as
type udt_Properties is table of varchar2(64) index by varchar2(64);
procedure LogCall (
a_RequestedTag varchar2,
a_ActualTag varchar2
) is
pragma autonomous_transaction;
begin
insert into PlsqlSessionCallbacks
values (a_RequestedTag, a_ActualTag, systimestamp);
commit;
end;
procedure ParseProperty (
a_Property varchar2,
a_Name out nocopy varchar2,
a_Value out nocopy varchar2
) is
t_Pos number;
begin
t_Pos := instr(a_Property, '=');
if t_Pos = 0 then
raise_application_error(-20000, 'Tag must contain key=value pairs');
end if;
a_Name := substr(a_Property, 1, t_Pos - 1);
a_Value := substr(a_Property, t_Pos + 1);
end;
procedure SetProperty (
a_Name varchar2,
a_Value varchar2
) is
t_ValidValues udt_Properties;
begin
if a_Name = 'TIME_ZONE' then
t_ValidValues('UTC') := 'UTC';
t_ValidValues('MST') := '-07:00';
elsif a_Name = 'NLS_DATE_FORMAT' then
t_ValidValues('SIMPLE') := 'YYYY-MM-DD HH24:MI';
t_ValidValues('FULL') := 'YYYY-MM-DD HH24:MI:SS';
else
raise_application_error(-20000, 'Unsupported session setting');
end if;
if not t_ValidValues.exists(a_Value) then
raise_application_error(-20000, 'Unsupported session setting');
end if;
execute immediate
'ALTER SESSION SET ' || a_Name || '=''' ||
t_ValidValues(a_Value) || '''';
end;
procedure ParseTag (
a_Tag varchar2,
a_Properties out nocopy udt_Properties
) is
t_PropertyName varchar2(64);
t_PropertyValue varchar2(64);
t_StartPos number;
t_EndPos number;
begin
t_StartPos := 1;
while t_StartPos < length(a_Tag) loop
t_EndPos := instr(a_Tag, ';', t_StartPos);
if t_EndPos = 0 then
t_EndPos := length(a_Tag) + 1;
end if;
ParseProperty(substr(a_Tag, t_StartPos, t_EndPos - t_StartPos),
t_PropertyName, t_PropertyValue);
a_Properties(t_PropertyName) := t_PropertyValue;
t_StartPos := t_EndPos + 1;
end loop;
end;
procedure TheCallback (
a_RequestedTag varchar2,
a_ActualTag varchar2
) is
t_RequestedProps udt_Properties;
t_ActualProps udt_Properties;
t_PropertyName varchar2(64);
begin
LogCall(a_RequestedTag, a_ActualTag);
ParseTag(a_RequestedTag, t_RequestedProps);
ParseTag(a_ActualTag, t_ActualProps);
t_PropertyName := t_RequestedProps.first;
while t_PropertyName is not null loop
if not t_ActualProps.exists(t_PropertyName) or
t_ActualProps(t_PropertyName) !=
t_RequestedProps(t_PropertyName) then
SetProperty(t_PropertyName, t_RequestedProps(t_PropertyName));
end if;
t_PropertyName := t_RequestedProps.next(t_PropertyName);
end loop;
end;
end;
/