Modify samples to follow the PEP 8 style guide.

This commit is contained in:
Anthony Tuininga 2020-12-08 11:46:17 -07:00
parent 6b9a7b011b
commit 30979c6a57
50 changed files with 389 additions and 396 deletions

View File

@ -26,7 +26,7 @@ Version 8.1 (TBD)
#) Tests can now be run with tox in order to automate testing of the different #) Tests can now be run with tox in order to automate testing of the different
environments that are supported. environments that are supported.
#) The value of prefetchrows for REF CURSOR variables is now honored. #) The value of prefetchrows for REF CURSOR variables is now honored.
#) Improved documentation and test suite. #) Improved documentation, samples and test suite.
Version 8.0.1 (August 2020) Version 8.0.1 (August 2020)

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -13,7 +13,7 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
import threading import threading
import time import time
@ -29,9 +29,11 @@ def ProcessMessages(message):
print("Queue name:", message.queueName) print("Queue name:", message.queueName)
print("Consumer name:", message.consumerName) print("Consumer name:", message.consumerName)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString(), events = True) connection = cx_Oracle.connect(sample_env.get_main_connect_string(),
events=True)
sub = connection.subscribe(namespace=cx_Oracle.SUBSCR_NAMESPACE_AQ, sub = connection.subscribe(namespace=cx_Oracle.SUBSCR_NAMESPACE_AQ,
name="DEMO_BOOK_QUEUE", callback=ProcessMessages, timeout=300) name="DEMO_BOOK_QUEUE", callback=ProcessMessages,
timeout=300)
print("Subscription:", sub) print("Subscription:", sub)
print("--> Connection:", sub.connection) print("--> Connection:", sub.connection)
print("--> Callback:", sub.callback) print("--> Callback:", sub.callback)

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -17,7 +17,7 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
# define constants used throughout the script; adjust as desired # define constants used throughout the script; adjust as desired
APP_CTX_NAMESPACE = "CLIENTCONTEXT" APP_CTX_NAMESPACE = "CLIENTCONTEXT"
@ -27,8 +27,8 @@ APP_CTX_ENTRIES = [
( APP_CTX_NAMESPACE, "ATTR3", "VALUE3" ) ( APP_CTX_NAMESPACE, "ATTR3", "VALUE3" )
] ]
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString(), connection = cx_Oracle.connect(sample_env.get_main_connect_string(),
appcontext = APP_CTX_ENTRIES) appcontext=APP_CTX_ENTRIES)
cursor = connection.cursor() cursor = connection.cursor()
for namespace, name, value in APP_CTX_ENTRIES: for namespace, name, value in APP_CTX_ENTRIES:
cursor.execute("select sys_context(:1, :2) from dual", (namespace, name)) cursor.execute("select sys_context(:1, :2) from dual", (namespace, name))

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -14,36 +14,36 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
cursor = connection.cursor() cursor = connection.cursor()
# show the number of rows for each parent ID as a means of verifying the # show the number of rows for each parent ID as a means of verifying the
# output from the delete statement # output from the delete statement
for parentId, count in cursor.execute(""" for parent_id, count in cursor.execute("""
select ParentId, count(*) select ParentId, count(*)
from ChildTable from ChildTable
group by ParentId group by ParentId
order by ParentId"""): order by ParentId"""):
print("Parent ID:", parentId, "has", int(count), "rows.") print("Parent ID:", parent_id, "has", int(count), "rows.")
print() print()
# delete the following parent IDs only # delete the following parent IDs only
parentIdsToDelete = [20, 30, 50] parent_ids_to_delete = [20, 30, 50]
print("Deleting Parent IDs:", parentIdsToDelete) print("Deleting Parent IDs:", parent_ids_to_delete)
print() print()
# enable array DML row counts for each iteration executed in executemany() # enable array DML row counts for each iteration executed in executemany()
cursor.executemany(""" cursor.executemany("""
delete from ChildTable delete from ChildTable
where ParentId = :1""", where ParentId = :1""",
[(i,) for i in parentIdsToDelete], [(i,) for i in parent_ids_to_delete],
arraydmlrowcounts = True) arraydmlrowcounts = True)
# display the number of rows deleted for each parent ID # display the number of rows deleted for each parent ID
rowCounts = cursor.getarraydmlrowcounts() row_counts = cursor.getarraydmlrowcounts()
for parentId, count in zip(parentIdsToDelete, rowCounts): for parent_id, count in zip(parent_ids_to_delete, row_counts):
print("Parent ID:", parentId, "deleted", count, "rows.") print("Parent ID:", parent_id, "deleted", count, "rows.")

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -16,13 +16,13 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
cursor = connection.cursor() cursor = connection.cursor()
# define data to insert # define data to insert
dataToInsert = [ data_to_insert = [
(1016, 10, 'Child B of Parent 10'), (1016, 10, 'Child B of Parent 10'),
(1017, 10, 'Child C of Parent 10'), (1017, 10, 'Child C of Parent 10'),
(1018, 20, 'Child D of Parent 20'), (1018, 20, 'Child D of Parent 20'),
@ -39,14 +39,14 @@ cursor.execute("""
from ChildTable""") from ChildTable""")
count, = cursor.fetchone() count, = cursor.fetchone()
print("number of rows in child table:", int(count)) print("number of rows in child table:", int(count))
print("number of rows to insert:", len(dataToInsert)) print("number of rows to insert:", len(data_to_insert))
# old method: executemany() with data errors results in stoppage after the # old method: executemany() with data errors results in stoppage after the
# first error takes place; the row count is updated to show how many rows # first error takes place; the row count is updated to show how many rows
# actually succeeded # actually succeeded
try: try:
cursor.executemany("insert into ChildTable values (:1, :2, :3)", cursor.executemany("insert into ChildTable values (:1, :2, :3)",
dataToInsert) data_to_insert)
except cx_Oracle.DatabaseError as e: except cx_Oracle.DatabaseError as e:
error, = e.args error, = e.args
print("FAILED with error:", error.message) print("FAILED with error:", error.message)
@ -64,12 +64,12 @@ connection.rollback()
# new method: executemany() with batch errors enabled (and array DML row counts # new method: executemany() with batch errors enabled (and array DML row counts
# also enabled) results in no immediate error being raised # also enabled) results in no immediate error being raised
cursor.executemany("insert into ChildTable values (:1, :2, :3)", dataToInsert, cursor.executemany("insert into ChildTable values (:1, :2, :3)",
batcherrors = True, arraydmlrowcounts = True) data_to_insert, batcherrors=True, arraydmlrowcounts=True)
# where errors have taken place, the row count is 0; otherwise it is 1 # where errors have taken place, the row count is 0; otherwise it is 1
rowCounts = cursor.getarraydmlrowcounts() row_counts = cursor.getarraydmlrowcounts()
print("Array DML row counts:", rowCounts) print("Array DML row counts:", row_counts)
# display the errors that have taken place # display the errors that have taken place
errors = cursor.getbatcherrors() errors = cursor.getbatcherrors()

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -9,9 +9,9 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
rows = [ (1, "First" ), rows = [ (1, "First" ),
(2, "Second" ), (2, "Second" ),

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -13,9 +13,9 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
cursor = connection.cursor() cursor = connection.cursor()
sql = 'select * from SampleQueryTab where id = :bvid' sql = 'select * from SampleQueryTab where id = :bvid'

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -17,7 +17,7 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
QUEUE_NAME = "DEMO_RAW_QUEUE" QUEUE_NAME = "DEMO_RAW_QUEUE"
PAYLOAD_DATA = [ PAYLOAD_DATA = [
@ -36,7 +36,7 @@ PAYLOAD_DATA = [
] ]
# connect to database # connect to database
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
cursor = connection.cursor() cursor = connection.cursor()
# create queue # create queue
@ -51,22 +51,22 @@ while queue.deqOne():
# enqueue a few messages # enqueue a few messages
print("Enqueuing messages...") print("Enqueuing messages...")
batchSize = 6 batch_size = 6
dataToEnq = PAYLOAD_DATA data_to_enqueue = PAYLOAD_DATA
while dataToEnq: while data_to_enqueue:
batchData = dataToEnq[:batchSize] batch_data = data_to_enqueue[:batch_size]
dataToEnq = dataToEnq[batchSize:] data_to_enqueue = data_to_enqueue[batch_size:]
messages = [connection.msgproperties(payload=d) for d in batchData] messages = [connection.msgproperties(payload=d) for d in batch_data]
for data in batchData: for data in batch_data:
print(data) print(data)
queue.enqMany(messages) queue.enqMany(messages)
connection.commit() connection.commit()
# dequeue the messages # dequeue the messages
print("\nDequeuing messages...") print("\nDequeuing messages...")
batchSize = 8 batch_size = 8
while True: while True:
messages = queue.deqMany(batchSize) messages = queue.deqMany(batch_size)
if not messages: if not messages:
break break
for props in messages: for props in messages:

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -18,7 +18,7 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
import time import time
registered = True registered = True
@ -47,7 +47,8 @@ def callback(message):
print("-" * 60) print("-" * 60)
print("=" * 60) print("=" * 60)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString(), events = True) connection = cx_Oracle.connect(sample_env.get_main_connect_string(),
events=True)
sub = connection.subscribe(callback = callback, timeout = 1800, sub = connection.subscribe(callback = callback, timeout = 1800,
qos = cx_Oracle.SUBSCR_QOS_QUERY | cx_Oracle.SUBSCR_QOS_ROWIDS) qos = cx_Oracle.SUBSCR_QOS_QUERY | cx_Oracle.SUBSCR_QOS_ROWIDS)
print("Subscription:", sub) print("Subscription:", sub)
@ -64,4 +65,3 @@ print("Registered query:", queryId)
while registered: while registered:
print("Waiting for notifications....") print("Waiting for notifications....")
time.sleep(5) time.sleep(5)

View File

@ -17,7 +17,7 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
import time import time
registered = True registered = True
@ -34,11 +34,11 @@ def callback(message):
if table.rows is None: if table.rows is None:
print("Too many row changes detected in table", table.name) print("Too many row changes detected in table", table.name)
continue continue
numRowsDeleted = 0 num_rows_deleted = 0
print(len(table.rows), "row changes detected in table", table.name) print(len(table.rows), "row changes detected in table", table.name)
for row in table.rows: for row in table.rows:
if row.operation & cx_Oracle.OPCODE_DELETE: if row.operation & cx_Oracle.OPCODE_DELETE:
numRowsDeleted += 1 num_rows_deleted += 1
continue continue
ops = [] ops = []
if row.operation & cx_Oracle.OPCODE_INSERT: if row.operation & cx_Oracle.OPCODE_INSERT:
@ -51,21 +51,22 @@ def callback(message):
from TestTempTable from TestTempTable
where rowid = :rid""", where rowid = :rid""",
rid=row.rowid) rid=row.rowid)
intCol, = cursor.fetchone() int_col, = cursor.fetchone()
print(" Row with IntCol", intCol, "was", " and ".join(ops)) print(" Row with IntCol", int_col, "was", " and ".join(ops))
if numRowsDeleted > 0: if num_rows_deleted > 0:
print(" ", numRowsDeleted, "rows deleted") print(" ", num_rows_deleted, "rows deleted")
print("=" * 60) print("=" * 60)
pool = cx_Oracle.SessionPool(SampleEnv.GetMainUser(), pool = cx_Oracle.SessionPool(user=sample_env.get_main_user(),
SampleEnv.GetMainPassword(), SampleEnv.GetConnectString(), min=2, password=sample_env.get_main_password(),
max=5, increment=1, events=True, threaded=True) dsn=sample_env.get_connect_string(), min=2,
max=5, increment=1, events=True, threaded=True)
with pool.acquire() as connection: with pool.acquire() as connection:
sub = connection.subscribe(callback=callback, timeout=1800, sub = connection.subscribe(callback=callback, timeout=1800,
qos=cx_Oracle.SUBSCR_QOS_QUERY | cx_Oracle.SUBSCR_QOS_ROWIDS) qos=cx_Oracle.SUBSCR_QOS_QUERY | cx_Oracle.SUBSCR_QOS_ROWIDS)
print("Subscription created with ID:", sub.id) print("Subscription created with ID:", sub.id)
queryId = sub.registerquery("select * from TestTempTable") query_id = sub.registerquery("select * from TestTempTable")
print("Registered query with ID:", queryId) print("Registered query with ID:", query_id)
while registered: while registered:
print("Waiting for notifications....") print("Waiting for notifications....")

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -14,9 +14,9 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
connection.callTimeout = 2000 connection.callTimeout = 2000
print("Call timeout set at", connection.callTimeout, "milliseconds...") print("Call timeout set at", connection.callTimeout, "milliseconds...")
@ -26,17 +26,16 @@ today, = cursor.fetchone()
print("Fetch of current date before timeout:", today) print("Fetch of current date before timeout:", today)
# dbms_session.sleep() replaces dbms_lock.sleep() from Oracle Database 18c # dbms_session.sleep() replaces dbms_lock.sleep() from Oracle Database 18c
sleepProcName = "dbms_session.sleep" \ sleep_proc_name = "dbms_session.sleep" \
if int(connection.version.split(".")[0]) >= 18 \ if int(connection.version.split(".")[0]) >= 18 \
else "dbms_lock.sleep" else "dbms_lock.sleep"
print("Sleeping...should time out...") print("Sleeping...should time out...")
try: try:
cursor.callproc(sleepProcName, (3,)) cursor.callproc(sleep_proc_name, (3,))
except cx_Oracle.DatabaseError as e: except cx_Oracle.DatabaseError as e:
print("ERROR:", e) print("ERROR:", e)
cursor.execute("select sysdate from dual") cursor.execute("select sysdate from dual")
today, = cursor.fetchone() today, = cursor.fetchone()
print("Fetch of current date after timeout:", today) print("Fetch of current date after timeout:", today)

View File

@ -21,17 +21,18 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
import threading import threading
# Create a Connection Pool # Create a Connection Pool
pool = cx_Oracle.SessionPool(SampleEnv.GetMainUser(), pool = cx_Oracle.SessionPool(user=sample_env.get_main_user(),
SampleEnv.GetMainPassword(), SampleEnv.GetConnectString(), min=2, password=sample_env.get_main_password(),
max=5, increment=1, threaded=True) dsn=sample_env.get_connect_string(), min=2,
max=5, increment=1, threaded=True)
# dbms_session.sleep() replaces dbms_lock.sleep() from Oracle Database 18c # dbms_session.sleep() replaces dbms_lock.sleep() from Oracle Database 18c
with pool.acquire() as conn: with pool.acquire() as conn:
sleepProcName = "dbms_session.sleep" \ sleep_proc_name = "dbms_session.sleep" \
if int(conn.version.split(".")[0]) >= 18 \ if int(conn.version.split(".")[0]) >= 18 \
else "dbms_lock.sleep" else "dbms_lock.sleep"
@ -62,7 +63,7 @@ def DoALock():
with pool.acquire() as conn: with pool.acquire() as conn:
cursor = conn.cursor() cursor = conn.cursor()
print("DoALock(): beginning execute...") print("DoALock(): beginning execute...")
cursor.callproc(sleepProcName, (5,)) cursor.callproc(sleep_proc_name, (5,))
print("DoALock(): done execute...") print("DoALock(): done execute...")

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -17,10 +17,10 @@
import cx_Oracle import cx_Oracle
import datetime import datetime
import SampleEnv import sample_env
# truncate table first so that script can be rerun # truncate table first so that script can be rerun
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
cursor = connection.cursor() cursor = connection.cursor()
print("Truncating table...") print("Truncating table...")
cursor.execute("truncate table TestTempTable") cursor.execute("truncate table TestTempTable")
@ -32,15 +32,14 @@ for i in range(5):
cursor.execute("insert into TestTempTable values (:1, :2)", data) cursor.execute("insert into TestTempTable values (:1, :2)", data)
# now delete them and use DML returning to return the data that was inserted # now delete them and use DML returning to return the data that was inserted
intCol = cursor.var(int) int_col = cursor.var(int)
stringCol = cursor.var(str) string_col = cursor.var(str)
print("Deleting data with DML returning...") print("Deleting data with DML returning...")
cursor.execute(""" cursor.execute("""
delete from TestTempTable delete from TestTempTable
returning IntCol, StringCol into :intCol, :stringCol""", returning IntCol, StringCol into :int_col, :string_col""",
intCol = intCol, int_col=int_col,
stringCol = stringCol) string_col=string_col)
print("Data returned:") print("Data returned:")
for intVal, stringVal in zip(intCol.getvalue(), stringCol.getvalue()): for int_val, string_val in zip(int_col.getvalue(), string_col.getvalue()):
print(tuple([intVal, stringVal])) print(tuple([int_val, string_val]))

View File

@ -33,12 +33,11 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
conn = cx_Oracle.connect(SampleEnv.GetDrcpConnectString(), cclass = "PYCLASS", conn = cx_Oracle.connect(sample_env.get_drcp_connect_string(),
purity = cx_Oracle.ATTR_PURITY_SELF) cclass="PYCLASS", purity=cx_Oracle.ATTR_PURITY_SELF)
cursor = conn.cursor() cursor = conn.cursor()
print("Performing query using DRCP...") print("Performing query using DRCP...")
for row in cursor.execute("select * from TestNumbers order by IntCol"): for row in cursor.execute("select * from TestNumbers order by IntCol"):
print(row) print(row)

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -18,7 +18,7 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
import time import time
registered = True registered = True
@ -44,7 +44,8 @@ def callback(message):
print("-" * 60) print("-" * 60)
print("=" * 60) print("=" * 60)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString(), events = True) connection = cx_Oracle.connect(sample_env.get_main_connect_string(),
events=True)
sub = connection.subscribe(callback = callback, timeout = 1800, sub = connection.subscribe(callback = callback, timeout = 1800,
qos = cx_Oracle.SUBSCR_QOS_ROWIDS) qos = cx_Oracle.SUBSCR_QOS_ROWIDS)
print("Subscription:", sub) print("Subscription:", sub)
@ -61,4 +62,3 @@ sub.registerquery("select * from TestTempTable")
while registered: while registered:
print("Waiting for notifications....") print("Waiting for notifications....")
time.sleep(5) time.sleep(5)

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -19,7 +19,7 @@
import cx_Oracle import cx_Oracle
# need to connect as SYSDBA or SYSOPER # need to connect as SYSDBA or SYSOPER
connection = cx_Oracle.connect("/", mode = cx_Oracle.SYSDBA) connection = cx_Oracle.connect("/", mode=cx_Oracle.SYSDBA)
# first shutdown() call must specify the mode, if DBSHUTDOWN_ABORT is used, # first shutdown() call must specify the mode, if DBSHUTDOWN_ABORT is used,
# there is no need for any of the other steps # there is no need for any of the other steps
@ -32,4 +32,3 @@ cursor.execute("alter database dismount")
# perform the final shutdown call # perform the final shutdown call
connection.shutdown(mode = cx_Oracle.DBSHUTDOWN_FINAL) connection.shutdown(mode = cx_Oracle.DBSHUTDOWN_FINAL)

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2017, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -20,12 +20,11 @@ import cx_Oracle
# the connection must be in PRELIM_AUTH mode # the connection must be in PRELIM_AUTH mode
connection = cx_Oracle.connect("/", connection = cx_Oracle.connect("/",
mode = cx_Oracle.SYSDBA | cx_Oracle.PRELIM_AUTH) mode=cx_Oracle.SYSDBA | cx_Oracle.PRELIM_AUTH)
connection.startup() connection.startup()
# the following statements must be issued in normal SYSDBA mode # the following statements must be issued in normal SYSDBA mode
connection = cx_Oracle.connect("/", mode = cx_Oracle.SYSDBA) connection = cx_Oracle.connect("/", mode=cx_Oracle.SYSDBA)
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("alter database mount") cursor.execute("alter database mount")
cursor.execute("alter database open") cursor.execute("alter database open")

View File

@ -9,9 +9,9 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
cursor = connection.cursor() cursor = connection.cursor()
# enable DBMS_OUTPUT # enable DBMS_OUTPUT

View File

@ -9,16 +9,16 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
def DropSamples(conn): def drop_samples(conn):
print("Dropping sample schemas and edition...") print("Dropping sample schemas and edition...")
SampleEnv.RunSqlScript(conn, "DropSamples", sample_env.run_sql_script(conn, "DropSamples",
main_user = SampleEnv.GetMainUser(), main_user=sample_env.get_main_user(),
edition_user = SampleEnv.GetEditionUser(), edition_user=sample_env.get_edition_user(),
edition_name = SampleEnv.GetEditionName()) edition_name=sample_env.get_edition_name())
if __name__ == "__main__": if __name__ == "__main__":
conn = cx_Oracle.connect(SampleEnv.GetAdminConnectString()) conn = cx_Oracle.connect(sample_env.get_admin_connect_string())
DropSamples(conn) drop_samples(conn)
print("Done.") print("Done.")

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -18,14 +18,14 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
import os import os
# connect to the editions user and create a procedure # connect to the editions user and create a procedure
editionConnectString = SampleEnv.GetEditionConnectString() edition_connect_string = sample_env.get_edition_connect_string()
connection = cx_Oracle.connect(editionConnectString) edition_name = sample_env.get_edition_name()
print("Edition should be None, actual value is:", connection = cx_Oracle.connect(edition_connect_string)
repr(connection.edition)) print("Edition should be None, actual value is:", repr(connection.edition))
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute(""" cursor.execute("""
create or replace function TestEditions return varchar2 as create or replace function TestEditions return varchar2 as
@ -34,12 +34,12 @@ cursor.execute("""
end;""") end;""")
result = cursor.callfunc("TestEditions", str) result = cursor.callfunc("TestEditions", str)
print("Function should return 'Base Procedure', actually returns:", print("Function should return 'Base Procedure', actually returns:",
repr(result)) repr(result))
# next, change the edition and recreate the procedure in the new edition # next, change the edition and recreate the procedure in the new edition
cursor.execute("alter session set edition = %s" % SampleEnv.GetEditionName()) cursor.execute("alter session set edition = %s" % edition_name)
print("Edition should be", repr(SampleEnv.GetEditionName().upper()), print("Edition should be", repr(edition_name.upper()),
"actual value is:", repr(connection.edition)) "actual value is:", repr(connection.edition))
cursor.execute(""" cursor.execute("""
create or replace function TestEditions return varchar2 as create or replace function TestEditions return varchar2 as
begin begin
@ -47,30 +47,29 @@ cursor.execute("""
end;""") end;""")
result = cursor.callfunc("TestEditions", str) result = cursor.callfunc("TestEditions", str)
print("Function should return 'Edition 1 Procedure', actually returns:", print("Function should return 'Edition 1 Procedure', actually returns:",
repr(result)) repr(result))
# next, change the edition back to the base edition and demonstrate that the # next, change the edition back to the base edition and demonstrate that the
# original function is being called # original function is being called
cursor.execute("alter session set edition = ORA$BASE") cursor.execute("alter session set edition = ORA$BASE")
result = cursor.callfunc("TestEditions", str) result = cursor.callfunc("TestEditions", str)
print("Function should return 'Base Procedure', actually returns:", print("Function should return 'Base Procedure', actually returns:",
repr(result)) repr(result))
# the edition can be set upon connection # the edition can be set upon connection
connection = cx_Oracle.connect(editionConnectString, connection = cx_Oracle.connect(edition_connect_string,
edition = SampleEnv.GetEditionName().upper()) edition=edition_name.upper())
cursor = connection.cursor() cursor = connection.cursor()
result = cursor.callfunc("TestEditions", str) result = cursor.callfunc("TestEditions", str)
print("Function should return 'Edition 1 Procedure', actually returns:", print("Function should return 'Edition 1 Procedure', actually returns:",
repr(result)) repr(result))
# it can also be set via the environment variable ORA_EDITION # it can also be set via the environment variable ORA_EDITION
os.environ["ORA_EDITION"] = SampleEnv.GetEditionName().upper() os.environ["ORA_EDITION"] = edition_name.upper()
connection = cx_Oracle.connect(editionConnectString) connection = cx_Oracle.connect(edition_connect_string)
print("Edition should be", repr(SampleEnv.GetEditionName().upper()), print("Edition should be", repr(edition_name.upper()),
"actual value is:", repr(connection.edition)) "actual value is:", repr(connection.edition))
cursor = connection.cursor() cursor = connection.cursor()
result = cursor.callfunc("TestEditions", str) result = cursor.callfunc("TestEditions", str)
print("Function should return 'Edition 1 Procedure', actually returns:", print("Function should return 'Edition 1 Procedure', actually returns:",
repr(result)) repr(result))

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -11,7 +11,7 @@
import collections import collections
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
class Connection(cx_Oracle.Connection): class Connection(cx_Oracle.Connection):
@ -22,9 +22,9 @@ class Connection(cx_Oracle.Connection):
class Cursor(cx_Oracle.Cursor): class Cursor(cx_Oracle.Cursor):
def execute(self, statement, args = None): def execute(self, statement, args = None):
prepareNeeded = (self.statement != statement) prepare_needed = (self.statement != statement)
result = super(Cursor, self).execute(statement, args or []) result = super(Cursor, self).execute(statement, args or [])
if prepareNeeded: if prepare_needed:
description = self.description description = self.description
if description: if description:
names = [d[0] for d in description] names = [d[0] for d in description]
@ -33,7 +33,7 @@ class Cursor(cx_Oracle.Cursor):
# create new subclassed connection and cursor # create new subclassed connection and cursor
connection = Connection(SampleEnv.GetMainConnectString()) connection = Connection(sample_env.get_main_connect_string())
cursor = connection.cursor() cursor = connection.cursor()
# the names are now available directly for each query executed # the names are now available directly for each query executed
@ -44,4 +44,3 @@ print()
for row in cursor.execute("select ChildId, Description from ChildTable"): for row in cursor.execute("select ChildId, Description from ChildTable"):
print(row.CHILDID, "->", row.DESCRIPTION) print(row.CHILDID, "->", row.DESCRIPTION)
print() print()

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -17,9 +17,9 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
cursor = connection.cursor() cursor = connection.cursor()
# use PL/SQL block to return two cursors # use PL/SQL block to return two cursors
@ -42,9 +42,8 @@ cursor.execute("""
end;""") end;""")
# display results # display results
for ix, resultSet in enumerate(cursor.getimplicitresults()): for ix, result_set in enumerate(cursor.getimplicitresults()):
print("Result Set #" + str(ix + 1)) print("Result Set #" + str(ix + 1))
for row in resultSet: for row in result_set:
print(row) print(row)
print() print()

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -16,18 +16,18 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
# create and populate Oracle objects # create and populate Oracle objects
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
typeObj = connection.gettype("MDSYS.SDO_GEOMETRY") type_obj = connection.gettype("MDSYS.SDO_GEOMETRY")
elementInfoTypeObj = connection.gettype("MDSYS.SDO_ELEM_INFO_ARRAY") element_info_type_obj = connection.gettype("MDSYS.SDO_ELEM_INFO_ARRAY")
ordinateTypeObj = connection.gettype("MDSYS.SDO_ORDINATE_ARRAY") ordinate_type_obj = connection.gettype("MDSYS.SDO_ORDINATE_ARRAY")
obj = typeObj.newobject() obj = type_obj.newobject()
obj.SDO_GTYPE = 2003 obj.SDO_GTYPE = 2003
obj.SDO_ELEM_INFO = elementInfoTypeObj.newobject() obj.SDO_ELEM_INFO = element_info_type_obj.newobject()
obj.SDO_ELEM_INFO.extend([1, 1003, 3]) obj.SDO_ELEM_INFO.extend([1, 1003, 3])
obj.SDO_ORDINATES = ordinateTypeObj.newobject() obj.SDO_ORDINATES = ordinate_type_obj.newobject()
obj.SDO_ORDINATES.extend([1, 1, 5, 7]) obj.SDO_ORDINATES.extend([1, 1, 5, 7])
print("Created object", obj) print("Created object", obj)
@ -50,7 +50,6 @@ if count == 0:
print("Removing any existing rows...") print("Removing any existing rows...")
cursor.execute("delete from TestGeometry") cursor.execute("delete from TestGeometry")
print("Adding row to table...") print("Adding row to table...")
cursor.execute("insert into TestGeometry values (1, :obj)", obj = obj) cursor.execute("insert into TestGeometry values (1, :obj)", obj=obj)
connection.commit() connection.commit()
print("Success!") print("Success!")

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -10,9 +10,9 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
row1 = [1, "First"] row1 = [1, "First"]
row2 = [2, "Second"] row2 = [2, "Second"]

View File

@ -17,7 +17,7 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
QUEUE_NAME = "DEMO_RAW_QUEUE_MULTI" QUEUE_NAME = "DEMO_RAW_QUEUE_MULTI"
PAYLOAD_DATA = [ PAYLOAD_DATA = [
@ -28,7 +28,7 @@ PAYLOAD_DATA = [
] ]
# connect to database # connect to database
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
cursor = connection.cursor() cursor = connection.cursor()
# create queue # create queue

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -17,7 +17,7 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
import decimal import decimal
BOOK_TYPE_NAME = "UDT_BOOK" BOOK_TYPE_NAME = "UDT_BOOK"
@ -30,12 +30,12 @@ BOOK_DATA = [
] ]
# connect to database # connect to database
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
cursor = connection.cursor() cursor = connection.cursor()
# create queue # create queue
booksType = connection.gettype(BOOK_TYPE_NAME) books_type = connection.gettype(BOOK_TYPE_NAME)
queue = connection.queue(QUEUE_NAME, booksType) queue = connection.queue(QUEUE_NAME, books_type)
queue.deqOptions.wait = cx_Oracle.DEQ_NO_WAIT queue.deqOptions.wait = cx_Oracle.DEQ_NO_WAIT
queue.deqOptions.navigation = cx_Oracle.DEQ_FIRST_MSG queue.deqOptions.navigation = cx_Oracle.DEQ_FIRST_MSG
@ -47,7 +47,7 @@ while queue.deqOne():
# enqueue a few messages # enqueue a few messages
print("Enqueuing messages...") print("Enqueuing messages...")
for title, authors, price in BOOK_DATA: for title, authors, price in BOOK_DATA:
book = booksType.newobject() book = books_type.newobject()
book.TITLE = title book.TITLE = title
book.AUTHORS = authors book.AUTHORS = authors
book.PRICE = price book.PRICE = price

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -14,14 +14,14 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
# create new empty object of the correct type # create new empty object of the correct type
# note the use of a PL/SQL type defined in a package # note the use of a PL/SQL type defined in a package
typeObj = connection.gettype("PKG_DEMO.UDT_STRINGLIST") type_obj = connection.gettype("PKG_DEMO.UDT_STRINGLIST")
obj = typeObj.newobject() obj = type_obj.newobject()
# call the stored procedure which will populate the object # call the stored procedure which will populate the object
cursor = connection.cursor() cursor = connection.cursor()
@ -44,4 +44,3 @@ print()
print("Values of collection as dictionary:") print("Values of collection as dictionary:")
print(obj.asdict()) print(obj.asdict())
print() print()

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -9,11 +9,10 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
cursor = connection.cursor() cursor = connection.cursor()
res = cursor.callfunc('myfunc', int, ('abc', 2)) res = cursor.callfunc('myfunc', int, ('abc', 2))
print(res) print(res)

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -10,12 +10,11 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
cursor = connection.cursor() cursor = connection.cursor()
myvar = cursor.var(int) myvar = cursor.var(int)
cursor.callproc('myproc', (123, myvar)) cursor.callproc('myproc', (123, myvar))
print(myvar.getvalue()) print(myvar.getvalue())

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -12,16 +12,16 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
import datetime import datetime
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
# create new object of the correct type # create new object of the correct type
# note the use of a PL/SQL record defined in a package # note the use of a PL/SQL record defined in a package
# a table record identified by TABLE%ROWTYPE can also be used # a table record identified by TABLE%ROWTYPE can also be used
typeObj = connection.gettype("PKG_DEMO.UDT_DEMORECORD") type_obj = connection.gettype("PKG_DEMO.UDT_DEMORECORD")
obj = typeObj.newobject() obj = type_obj.newobject()
obj.NUMBERVALUE = 6 obj.NUMBERVALUE = 6
obj.STRINGVALUE = "Test String" obj.STRINGVALUE = "Test String"
obj.DATEVALUE = datetime.datetime(2016, 5, 28) obj.DATEVALUE = datetime.datetime(2016, 5, 28)
@ -44,4 +44,3 @@ print("STRINGVALUE ->", obj.STRINGVALUE)
print("DATEVALUE ->", obj.DATEVALUE) print("DATEVALUE ->", obj.DATEVALUE)
print("BOOLEANVALUE ->", obj.BOOLEANVALUE) print("BOOLEANVALUE ->", obj.BOOLEANVALUE)
print() print()

View File

@ -9,9 +9,9 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
sql = """ sql = """
select * from SampleQueryTab select * from SampleQueryTab

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -12,9 +12,9 @@
import time import time
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
start = time.time() start = time.time()
@ -26,4 +26,3 @@ res = cursor.fetchall()
elapsed = (time.time() - start) elapsed = (time.time() - start)
print("Retrieved", len(res), "rows in", elapsed, "seconds") print("Retrieved", len(res), "rows in", elapsed, "seconds")

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -16,7 +16,7 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
QUEUE_NAME = "DEMO_RAW_QUEUE" QUEUE_NAME = "DEMO_RAW_QUEUE"
PAYLOAD_DATA = [ PAYLOAD_DATA = [
@ -27,7 +27,7 @@ PAYLOAD_DATA = [
] ]
# connect to database # connect to database
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
cursor = connection.cursor() cursor = connection.cursor()
# create queue # create queue

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -8,9 +8,9 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
cursor = connection.cursor() cursor = connection.cursor()
ref_cursor = connection.cursor() ref_cursor = connection.cursor()

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -19,34 +19,34 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
def OutputTypeHandler(cursor, name, defaultType, size, precision, scale): def output_type_handler(cursor, name, default_type, size, precision, scale):
if defaultType == cx_Oracle.CLOB: if default_type == cx_Oracle.CLOB:
return cursor.var(cx_Oracle.LONG_STRING, arraysize = cursor.arraysize) return cursor.var(cx_Oracle.LONG_STRING, arraysize=cursor.arraysize)
if defaultType == cx_Oracle.BLOB: if default_type == cx_Oracle.BLOB:
return cursor.var(cx_Oracle.LONG_BINARY, arraysize = cursor.arraysize) return cursor.var(cx_Oracle.LONG_BINARY, arraysize=cursor.arraysize)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
connection.outputtypehandler = OutputTypeHandler connection.outputtypehandler = output_type_handler
cursor = connection.cursor() cursor = connection.cursor()
# add some data to the tables # add some data to the tables
print("Populating tables with data...") print("Populating tables with data...")
cursor.execute("truncate table TestClobs") cursor.execute("truncate table TestClobs")
cursor.execute("truncate table TestBlobs") cursor.execute("truncate table TestBlobs")
longString = "" long_string = ""
for i in range(10): for i in range(10):
char = chr(ord('A') + i) char = chr(ord('A') + i)
longString += char * 25000 long_string += char * 25000
# uncomment the line below for cx_Oracle 5.3 and earlier # uncomment the line below for cx_Oracle 5.3 and earlier
# cursor.setinputsizes(None, cx_Oracle.LONG_STRING) # cursor.setinputsizes(None, cx_Oracle.LONG_STRING)
cursor.execute("insert into TestClobs values (:1, :2)", cursor.execute("insert into TestClobs values (:1, :2)",
(i + 1, "STRING " + longString)) (i + 1, "STRING " + long_string))
# uncomment the line below for cx_Oracle 5.3 and earlier # uncomment the line below for cx_Oracle 5.3 and earlier
# cursor.setinputsizes(None, cx_Oracle.LONG_BINARY) # cursor.setinputsizes(None, cx_Oracle.LONG_BINARY)
cursor.execute("insert into TestBlobs values (:1, :2)", cursor.execute("insert into TestBlobs values (:1, :2)",
(i + 1, longString.encode("ascii"))) (i + 1, long_string.encode("ascii")))
connection.commit() connection.commit()
# fetch the data and show the results # fetch the data and show the results
@ -57,8 +57,8 @@ cursor.execute("""
ClobCol ClobCol
from TestClobs from TestClobs
order by IntCol""") order by IntCol""")
for intCol, value in cursor: for int_col, value in cursor:
print("Row:", intCol, "string of length", len(value)) print("Row:", int_col, "string of length", len(value))
print() print()
print("BLOBS returned as bytes") print("BLOBS returned as bytes")
cursor.execute(""" cursor.execute("""
@ -67,6 +67,5 @@ cursor.execute("""
BlobCol BlobCol
from TestBlobs from TestBlobs
order by IntCol""") order by IntCol""")
for intCol, value in cursor: for int_col, value in cursor:
print("Row:", intCol, "string of length", value and len(value) or 0) print("Row:", int_col, "string of length", value and len(value) or 0)

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -16,16 +16,15 @@
import cx_Oracle import cx_Oracle
import decimal import decimal
import SampleEnv import sample_env
def OutputTypeHandler(cursor, name, defaultType, size, precision, scale): def output_type_handler(cursor, name, defaultType, size, precision, scale):
if defaultType == cx_Oracle.NUMBER: if defaultType == cx_Oracle.NUMBER:
return cursor.var(decimal.Decimal, arraysize = cursor.arraysize) return cursor.var(decimal.Decimal, arraysize = cursor.arraysize)
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
connection.outputtypehandler = OutputTypeHandler connection.outputtypehandler = output_type_handler
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute("select * from TestNumbers") cursor.execute("select * from TestNumbers")
for row in cursor: for row in cursor:
print("Row:", row) print("Row:", row)

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -17,7 +17,7 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
class Test(object): class Test(object):
@ -26,7 +26,7 @@ class Test(object):
self.b = b self.b = b
self.c = c self.c = c
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
cursor = connection.cursor() cursor = connection.cursor()
# change this to False if you want to create the table yourself using SQL*Plus # change this to False if you want to create the table yourself using SQL*Plus
@ -55,4 +55,3 @@ cursor.rowfactory = Test
print("Rows:") print("Rows:")
for row in cursor: for row in cursor:
print("a = %s, b = %s, c = %s" % (row.a, row.b, row.c)) print("a = %s, b = %s, c = %s" % (row.a, row.b, row.c))

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -17,9 +17,9 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
# show all of the rows available in the table # show all of the rows available in the table
cursor = connection.cursor() cursor = connection.cursor()
@ -68,4 +68,3 @@ cursor.scroll(-4)
print("SKIP BACK 4 ROWS") print("SKIP BACK 4 ROWS")
print(cursor.fetchone()) print(cursor.fetchone())
print() print()

View File

@ -21,7 +21,7 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
# define a dictionary of NLS_DATE_FORMAT formats supported by this sample # define a dictionary of NLS_DATE_FORMAT formats supported by this sample
SUPPORTED_FORMATS = { SUPPORTED_FORMATS = {
@ -42,18 +42,18 @@ SUPPORTED_KEYS = {
} }
# define session callback # define session callback
def InitSession(conn, requestedTag): def init_session(conn, requested_tag):
# display the requested and actual tags # display the requested and actual tags
print("InitSession(): requested tag=%r, actual tag=%r" % \ print("init_session(): requested tag=%r, actual tag=%r" % \
(requestedTag, conn.tag)) (requested_tag, conn.tag))
# tags are expected to be in the form "key1=value1;key2=value2" # tags are expected to be in the form "key1=value1;key2=value2"
# in this example, they are used to set NLS parameters and the tag is # in this example, they are used to set NLS parameters and the tag is
# parsed to validate it # parsed to validate it
if requestedTag is not None: if requested_tag is not None:
stateParts = [] stateParts = []
for directive in requestedTag.split(";"): for directive in requested_tag.split(";"):
parts = directive.split("=") parts = directive.split("=")
if len(parts) != 2: if len(parts) != 2:
raise ValueError("Tag must contain key=value pairs") raise ValueError("Tag must contain key=value pairs")
@ -74,13 +74,15 @@ def InitSession(conn, requestedTag):
# assign the requested tag to the connection so that when the connection # assign the requested tag to the connection so that when the connection
# is closed, it will automatically be retagged; note that if the requested # is closed, it will automatically be retagged; note that if the requested
# tag is None (no tag was requested) this has no effect # tag is None (no tag was requested) this has no effect
conn.tag = requestedTag conn.tag = requested_tag
# create pool with session callback defined # create pool with session callback defined
pool = cx_Oracle.SessionPool(SampleEnv.GetMainUser(), pool = cx_Oracle.SessionPool(user=sample_env.get_main_user(),
SampleEnv.GetMainPassword(), SampleEnv.GetConnectString(), min=2, password=sample_env.get_main_password(),
max=5, increment=1, threaded=True, sessionCallback=InitSession) dsn=sample_env.get_connect_string(), min=2, max=5,
increment=1, threaded=True,
sessionCallback=init_session)
# acquire session without specifying a tag; since the session returned is # acquire session without specifying a tag; since the session returned is
# newly created, the callback will be invoked but since there is no tag # newly created, the callback will be invoked but since there is no tag

View File

@ -23,13 +23,14 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
# create pool with session callback defined # create pool with session callback defined
pool = cx_Oracle.SessionPool(SampleEnv.GetMainUser(), pool = cx_Oracle.SessionPool(user=sample_env.get_main_user(),
SampleEnv.GetMainPassword(), SampleEnv.GetConnectString(), min=2, password=sample_env.get_main_password(),
max=5, increment=1, threaded=True, dsn=sample_env.get_connect_string(), min=2, max=5,
sessionCallback="pkg_SessionCallback.TheCallback") increment=1, threaded=True,
sessionCallback="pkg_SessionCallback.TheCallback")
# truncate table logging calls to PL/SQL session callback # truncate table logging calls to PL/SQL session callback
with pool.acquire() as conn: with pool.acquire() as conn:

View File

@ -12,22 +12,22 @@
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
import DropSamples import DropSamples
# connect as administrative user (usually SYSTEM or ADMIN) # connect as administrative user (usually SYSTEM or ADMIN)
conn = cx_Oracle.connect(SampleEnv.GetAdminConnectString()) conn = cx_Oracle.connect(sample_env.get_admin_connect_string())
# drop existing users and editions, if applicable # drop existing users and editions, if applicable
DropSamples.DropSamples(conn) DropSamples.drop_samples(conn)
# create sample schema and edition # create sample schema and edition
print("Creating sample schemas and edition...") print("Creating sample schemas and edition...")
SampleEnv.RunSqlScript(conn, "SetupSamples", sample_env.run_sql_script(conn, "SetupSamples",
main_user = SampleEnv.GetMainUser(), main_user=sample_env.get_main_user(),
main_password = SampleEnv.GetMainPassword(), main_password=sample_env.get_main_password(),
edition_user = SampleEnv.GetEditionUser(), edition_user=sample_env.get_edition_user(),
edition_password = SampleEnv.GetEditionPassword(), edition_password=sample_env.get_edition_password(),
edition_name = SampleEnv.GetEditionName()) edition_name=sample_env.get_edition_name())
print("Done.") print("Done.")

View File

@ -16,19 +16,20 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
pool = cx_Oracle.SessionPool(SampleEnv.GetMainUser(), pool = cx_Oracle.SessionPool(user=sample_env.get_main_user(),
SampleEnv.GetMainPassword(), SampleEnv.GetConnectString(), min=1, password=sample_env.get_main_password(),
max=5, increment=1) dsn=sample_env.get_connect_string(), min=1, max=5,
increment=1)
def ConnectAndDisplay(shardingKey): def connect_and_display(sharding_key):
print("Connecting with sharding key:", shardingKey) print("Connecting with sharding key:", sharding_key)
with pool.acquire(shardingkey=[shardingKey]) as conn: with pool.acquire(shardingkey=[sharding_key]) as conn:
cursor = conn.cursor() cursor = conn.cursor()
cursor.execute("select sys_context('userenv', 'db_name') from dual") cursor.execute("select sys_context('userenv', 'db_name') from dual")
name, = cursor.fetchone() name, = cursor.fetchone()
print("--> connected to database", name) print("--> connected to database", name)
ConnectAndDisplay(100) connect_and_display(100)
ConnectAndDisplay(167) connect_and_display(167)

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -13,9 +13,9 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
# The general recommendation for simple SODA usage is to enable autocommit # The general recommendation for simple SODA usage is to enable autocommit
connection.autocommit = True connection.autocommit = True
@ -27,12 +27,17 @@ soda = connection.getSodaDatabase()
# This will open an existing collection, if the name is already in use. # This will open an existing collection, if the name is already in use.
collection = soda.createCollection("mycollection") collection = soda.createCollection("mycollection")
indexSpec = { 'name': 'CITY_IDX', index_spec = {
'fields': [ { 'name': 'CITY_IDX',
'path': 'address.city', 'fields': [
'datatype': 'string', {
'order': 'asc' } ] } 'path': 'address.city',
collection.createIndex(indexSpec) 'datatype': 'string',
'order': 'asc'
}
]
}
collection.createIndex(index_spec)
# Insert a document. # Insert a document.
# A system generated key is created by default. # A system generated key is created by default.
@ -85,4 +90,3 @@ print('Collection has', c, 'documents')
# Drop the collection # Drop the collection
if collection.drop(): if collection.drop():
print('Collection was dropped') print('Collection was dropped')

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2019, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -13,9 +13,9 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
# the general recommendation for simple SODA usage is to enable autocommit # the general recommendation for simple SODA usage is to enable autocommit
connection.autocommit = True connection.autocommit = True
@ -30,7 +30,7 @@ collection = soda.createCollection("SodaBulkInsert")
collection.find().remove() collection.find().remove()
# define some documents that will be stored # define some documents that will be stored
inDocs = [ in_docs = [
dict(name="Sam", age=8), dict(name="Sam", age=8),
dict(name="George", age=46), dict(name="George", age=46),
dict(name="Bill", age=35), dict(name="Bill", age=35),
@ -40,8 +40,8 @@ inDocs = [
] ]
# perform bulk insert # perform bulk insert
resultDocs = collection.insertManyAndGet(inDocs) result_docs = collection.insertManyAndGet(in_docs)
for doc in resultDocs: for doc in result_docs:
print("Inserted SODA document with key", doc.key) print("Inserted SODA document with key", doc.key)
print() print()

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2018, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2018, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -22,13 +22,13 @@
# dependencies (see http://geopandas.org/install.html). # dependencies (see http://geopandas.org/install.html).
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import SampleEnv import sample_env
import cx_Oracle import cx_Oracle
from shapely.wkb import loads from shapely.wkb import loads
import geopandas as gpd import geopandas as gpd
# create Oracle connection and cursor objects # create Oracle connection and cursor objects
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
cursor = connection.cursor() cursor = connection.cursor()
# enable autocommit to avoid the additional round trip to the database to # enable autocommit to avoid the additional round trip to the database to
@ -38,10 +38,10 @@ connection.autocommit = True
# define output type handler to fetch LOBs, avoiding the second round trip to # define output type handler to fetch LOBs, avoiding the second round trip to
# the database to read the LOB contents # the database to read the LOB contents
def OutputTypeHandler(cursor, name, defaultType, size, precision, scale): def output_type_handler(cursor, name, default_type, size, precision, scale):
if defaultType == cx_Oracle.BLOB: if default_type == cx_Oracle.BLOB:
return cursor.var(cx_Oracle.LONG_BINARY, arraysize = cursor.arraysize) return cursor.var(cx_Oracle.LONG_BINARY, arraysize=cursor.arraysize)
connection.outputtypehandler = OutputTypeHandler connection.outputtypehandler = output_type_handler
# drop and create table # drop and create table
print("Dropping and creating table...") print("Dropping and creating table...")
@ -60,23 +60,23 @@ cursor.execute("""
)""") )""")
# acquire types used for creating SDO_GEOMETRY objects # acquire types used for creating SDO_GEOMETRY objects
typeObj = connection.gettype("MDSYS.SDO_GEOMETRY") type_obj = connection.gettype("MDSYS.SDO_GEOMETRY")
elementInfoTypeObj = connection.gettype("MDSYS.SDO_ELEM_INFO_ARRAY") element_info_type_obj = connection.gettype("MDSYS.SDO_ELEM_INFO_ARRAY")
ordinateTypeObj = connection.gettype("MDSYS.SDO_ORDINATE_ARRAY") ordinate_type_obj = connection.gettype("MDSYS.SDO_ORDINATE_ARRAY")
# define function for creating an SDO_GEOMETRY object # define function for creating an SDO_GEOMETRY object
def CreateGeometryObj(*ordinates): def create_geometry_obj(*ordinates):
geometry = typeObj.newobject() geometry = type_obj.newobject()
geometry.SDO_GTYPE = 2003 geometry.SDO_GTYPE = 2003
geometry.SDO_SRID = 8307 geometry.SDO_SRID = 8307
geometry.SDO_ELEM_INFO = elementInfoTypeObj.newobject() geometry.SDO_ELEM_INFO = element_info_type_obj.newobject()
geometry.SDO_ELEM_INFO.extend([1, 1003, 1]) geometry.SDO_ELEM_INFO.extend([1, 1003, 1])
geometry.SDO_ORDINATES = ordinateTypeObj.newobject() geometry.SDO_ORDINATES = ordinate_type_obj.newobject()
geometry.SDO_ORDINATES.extend(ordinates) geometry.SDO_ORDINATES.extend(ordinates)
return geometry return geometry
# create SDO_GEOMETRY objects for three adjacent states in the USA # create SDO_GEOMETRY objects for three adjacent states in the USA
geometryNevada = CreateGeometryObj(-114.052025, 37.103989, -114.049797, geometry_nevada = create_geometry_obj(-114.052025, 37.103989, -114.049797,
37.000423, -113.484375, 37, -112.898598, 37.000401,-112.539604, 37.000423, -113.484375, 37, -112.898598, 37.000401,-112.539604,
37.000683, -112, 37.000977, -111.412048, 37.001514, -111.133018, 37.000683, -112, 37.000977, -111.412048, 37.001514, -111.133018,
37.00079,-110.75, 37.003201, -110.5, 37.004265, -110.469505, 36.998001, 37.00079,-110.75, 37.003201, -110.5, 37.004265, -110.469505, 36.998001,
@ -96,7 +96,7 @@ geometryNevada = CreateGeometryObj(-114.052025, 37.103989, -114.049797,
-114.049339, 38.572968, -114.049095, 38.14864, -114.0476, -114.049339, 38.572968, -114.049095, 38.14864, -114.0476,
37.80946,-114.05098, 37.746284, -114.051666, 37.604805, -114.052025, 37.80946,-114.05098, 37.746284, -114.051666, 37.604805, -114.052025,
37.103989) 37.103989)
geometryWyoming = CreateGeometryObj(-111.045815, 41.251774, -111.045982, geometry_wyoming = create_geometry_obj(-111.045815, 41.251774, -111.045982,
40.998013, -110.5, 40.994801, -110.047768, 40.997696, -110, 40.997398, 40.998013, -110.5, 40.994801, -110.047768, 40.997696, -110, 40.997398,
-109.534233, 40.998184, -109.2313, 41.002102, -109.0494, 41.000702, -109.534233, 40.998184, -109.2313, 41.002102, -109.0494, 41.000702,
-108.525368, 40.999634, -107.917793, 41.002071, -107.317177, 41.002956, -108.525368, 40.999634, -107.917793, 41.002071, -107.317177, 41.002956,
@ -120,7 +120,7 @@ geometryWyoming = CreateGeometryObj(-111.045815, 41.251774, -111.045982,
-111.043846, 43.3158, -111.043381, 43.02013, -111.042786, 42.719578, -111.043846, 43.3158, -111.043381, 43.02013, -111.042786, 42.719578,
-111.045967, 42.513187, -111.045944, 42.001633, -111.045097, 41.579899, -111.045967, 42.513187, -111.045944, 42.001633, -111.045097, 41.579899,
-111.045815, 41.251774) -111.045815, 41.251774)
geometryColorado = CreateGeometryObj(-109.045143, 37.375, -109.044571, geometry_colorado = create_geometry_obj(-109.045143, 37.375, -109.044571,
36.999088, -108.378571, 36.999516, -107.481133, 37, -107.420311, 37, 36.999088, -108.378571, 36.999516, -107.481133, 37, -107.420311, 37,
-106.876701, 37.00013, -106.869209, 36.992416, -106.475639, 36.993748, -106.876701, 37.00013, -106.869209, 36.992416, -106.475639, 36.993748,
-106.006058, 36.995327, -105.717834, 36.995823, -105.220055, 36.995144, -106.006058, 36.995327, -105.717834, 36.995823, -105.220055, 36.995144,
@ -151,9 +151,9 @@ geometryColorado = CreateGeometryObj(-109.045143, 37.375, -109.044571,
# will skip the metadata and indexes. # will skip the metadata and indexes.
print("Adding rows to table...") print("Adding rows to table...")
data = [ data = [
('Nevada', geometryNevada), ('Nevada', geometry_nevada),
('Colorado', geometryColorado), ('Colorado', geometry_colorado),
('Wyoming', geometryWyoming) ('Wyoming', geometry_wyoming)
] ]
cursor.executemany('insert into TestStates values (:state, :obj)', data) cursor.executemany('insert into TestStates values (:state, :obj)', data)
@ -168,7 +168,7 @@ cursor.executemany('insert into TestStates values (:state, :obj)', data)
cursor.execute(""" cursor.execute("""
SELECT state, sdo_util.to_wkbgeometry(geometry) SELECT state, sdo_util.to_wkbgeometry(geometry)
FROM TestStates""") FROM TestStates""")
gdf = gpd.GeoDataFrame(cursor.fetchall(), columns = ['state', 'wkbgeometry']) gdf = gpd.GeoDataFrame(cursor.fetchall(), columns=['state', 'wkbgeometry'])
# create GeoSeries to replace the WKB geometry column # create GeoSeries to replace the WKB geometry column
gdf['geometry'] = gpd.GeoSeries(gdf['wkbgeometry'].apply(lambda x: loads(x))) gdf['geometry'] = gpd.GeoSeries(gdf['wkbgeometry'].apply(lambda x: loads(x)))
@ -183,4 +183,3 @@ print(gdf)
print() print()
print("GeoPandas combining the 3 geometries into a single geometry...") print("GeoPandas combining the 3 geometries into a single geometry...")
print(gdf.unary_union) print(gdf.unary_union)

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -11,7 +11,7 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
# sample subclassed connection which overrides the constructor (so no # sample subclassed connection which overrides the constructor (so no
# parameters are required) and the cursor() method (so that the subclassed # parameters are required) and the cursor() method (so that the subclassed
@ -19,9 +19,9 @@ import SampleEnv
class Connection(cx_Oracle.Connection): class Connection(cx_Oracle.Connection):
def __init__(self): def __init__(self):
connectString = SampleEnv.GetMainConnectString() connect_string = sample_env.get_main_connect_string()
print("CONNECT to database") print("CONNECT to database")
return super(Connection, self).__init__(connectString) return super(Connection, self).__init__(connect_string)
def cursor(self): def cursor(self):
return Cursor(self) return Cursor(self)
@ -34,8 +34,8 @@ class Cursor(cx_Oracle.Cursor):
def execute(self, statement, args): def execute(self, statement, args):
print("EXECUTE", statement) print("EXECUTE", statement)
print("ARGS:") print("ARGS:")
for argIndex, arg in enumerate(args): for arg_index, arg in enumerate(args):
print(" ", argIndex + 1, "=>", repr(arg)) print(" ", arg_index + 1, "=>", repr(arg))
return super(Cursor, self).execute(statement, args) return super(Cursor, self).execute(statement, args)
def fetchone(self): def fetchone(self):
@ -51,4 +51,3 @@ cursor = connection.cursor()
cursor.execute("select count(*) from ChildTable where ParentId = :1", (30,)) cursor.execute("select count(*) from ChildTable where ParentId = :1", (30,))
count, = cursor.fetchone() count, = cursor.fetchone()
print("COUNT:", int(count)) print("COUNT:", int(count))

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -34,16 +34,16 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
import cx_Oracle import cx_Oracle
import SampleEnv import sample_env
import sys import sys
# constants # constants
CONNECT_STRING = "localhost/orcl-tg" CONNECT_STRING = "localhost/orcl-tg"
# create transaction and generate a recoverable error # create transaction and generate a recoverable error
pool = cx_Oracle.SessionPool(SampleEnv.GetMainUser(), pool = cx_Oracle.SessionPool(user=sample_env.get_main_user(),
SampleEnv.GetMainPassword(), CONNECT_STRING, min=1, password=sample_env.get_main_password(),
max=9, increment=2) dsn=CONNECT_STRING, min=1, max=9, increment=2)
connection = pool.acquire() connection = pool.acquire()
cursor = connection.cursor() cursor = connection.cursor()
cursor.execute(""" cursor.execute("""
@ -53,7 +53,7 @@ cursor.execute("""
insert into TestTempTable insert into TestTempTable
values (1, null)""") values (1, null)""")
input("Please kill %s session now. Press ENTER when complete." % \ input("Please kill %s session now. Press ENTER when complete." % \
SampleEnv.GetMainUser()) sample_env.get_main_user())
try: try:
connection.commit() # this should fail connection.commit() # this should fail
sys.exit("Session was not killed. Terminating.") sys.exit("Session was not killed. Terminating.")
@ -69,8 +69,8 @@ pool.drop(connection)
# check if previous transaction completed # check if previous transaction completed
connection = pool.acquire() connection = pool.acquire()
cursor = connection.cursor() cursor = connection.cursor()
args = (cx_Oracle.Binary(ltxid), cursor.var(bool), cursor.var(bool))
_, committed, completed = cursor.callproc("dbms_app_cont.get_ltxid_outcome", _, committed, completed = cursor.callproc("dbms_app_cont.get_ltxid_outcome",
(cx_Oracle.Binary(ltxid), cursor.var(bool), cursor.var(bool))) args)
print("Failed transaction was committed:", committed) print("Failed transaction was committed:", committed)
print("Failed call was completed:", completed) print("Failed call was completed:", completed)

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2016, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2016, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -19,46 +19,47 @@
import cx_Oracle import cx_Oracle
import datetime import datetime
import SampleEnv import sample_env
con = cx_Oracle.connect(SampleEnv.GetMainConnectString()) con = cx_Oracle.connect(sample_env.get_main_connect_string())
objType = con.gettype("UDT_BUILDING") obj_type = con.gettype("UDT_BUILDING")
class Building(object): class Building(object):
def __init__(self, buildingId, description, numFloors, dateBuilt): def __init__(self, building_id, description, num_floors, dateBuilt):
self.buildingId = buildingId self.building_id = building_id
self.description = description self.description = description
self.numFloors = numFloors self.num_floors = num_floors
self.dateBuilt = dateBuilt self.dateBuilt = dateBuilt
def __repr__(self): def __repr__(self):
return "<Building %s: %s>" % (self.buildingId, self.description) return "<Building %s: %s>" % (self.building_id, self.description)
def BuildingInConverter(value): def building_in_converter(value):
obj = objType.newobject() obj = obj_type.newobject()
obj.BUILDINGID = value.buildingId obj.BUILDINGID = value.building_id
obj.DESCRIPTION = value.description obj.DESCRIPTION = value.description
obj.NUMFLOORS = value.numFloors obj.NUMFLOORS = value.num_floors
obj.DATEBUILT = value.dateBuilt obj.DATEBUILT = value.dateBuilt
return obj return obj
def BuildingOutConverter(obj): def building_out_converter(obj):
return Building(int(obj.BUILDINGID), obj.DESCRIPTION, int(obj.NUMFLOORS), return Building(int(obj.BUILDINGID), obj.DESCRIPTION, int(obj.NUMFLOORS),
obj.DATEBUILT) obj.DATEBUILT)
def InputTypeHandler(cursor, value, numElements): def input_type_handler(cursor, value, numElements):
if isinstance(value, Building): if isinstance(value, Building):
return cursor.var(cx_Oracle.OBJECT, arraysize = numElements, return cursor.var(cx_Oracle.OBJECT, arraysize = numElements,
inconverter = BuildingInConverter, typename = objType.name) inconverter = building_in_converter, typename = obj_type.name)
def OutputTypeHandler(cursor, name, defaultType, size, precision, scale): def output_type_handler(cursor, name, default_type, size, precision, scale):
if defaultType == cx_Oracle.OBJECT: if default_type == cx_Oracle.OBJECT:
return cursor.var(cx_Oracle.OBJECT, arraysize = cursor.arraysize, return cursor.var(cx_Oracle.OBJECT, arraysize=cursor.arraysize,
outconverter = BuildingOutConverter, typename = objType.name) outconverter=building_out_converter,
typename=obj_type.name)
buildings = [ buildings = [
Building(1, "The First Building", 5, datetime.date(2007, 5, 18)), Building(1, "The First Building", 5, datetime.date(2007, 5, 18)),
@ -67,11 +68,11 @@ buildings = [
] ]
cur = con.cursor() cur = con.cursor()
cur.inputtypehandler = InputTypeHandler cur.inputtypehandler = input_type_handler
for building in buildings: for building in buildings:
try: try:
cur.execute("insert into TestBuildings values (:1, :2)", cur.execute("insert into TestBuildings values (:1, :2)",
(building.buildingId, building)) (building.building_id, building))
except cx_Oracle.DatabaseError as e: except cx_Oracle.DatabaseError as e:
error, = e.args error, = e.args
print("CONTEXT:", error.context) print("CONTEXT:", error.context)
@ -84,9 +85,8 @@ for row in cur.execute("select * from TestBuildings order by BuildingId"):
print() print()
cur = con.cursor() cur = con.cursor()
cur.outputtypehandler = OutputTypeHandler cur.outputtypehandler = output_type_handler
print("WITH OUTPUT TYPE HANDLER:") print("WITH OUTPUT TYPE HANDLER:")
for row in cur.execute("select * from TestBuildings order by BuildingId"): for row in cur.execute("select * from TestBuildings order by BuildingId"):
print(row) print(row)
print() print()

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved.
# #
# Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved. # Portions Copyright 2007-2015, Anthony Tuininga. All rights reserved.
# #
@ -17,7 +17,7 @@
import cx_Oracle import cx_Oracle
import datetime import datetime
import SampleEnv import sample_env
DATA = [ DATA = [
(1, "String #1", datetime.datetime(2017, 4, 4)), (1, "String #1", datetime.datetime(2017, 4, 4)),
@ -26,7 +26,7 @@ DATA = [
] ]
# truncate table so sample can be rerun # truncate table so sample can be rerun
connection = cx_Oracle.connect(SampleEnv.GetMainConnectString()) connection = cx_Oracle.connect(sample_env.get_main_connect_string())
cursor = connection.cursor() cursor = connection.cursor()
print("Truncating table...") print("Truncating table...")
cursor.execute("truncate table TestUniversalRowids") cursor.execute("truncate table TestUniversalRowids")
@ -50,8 +50,7 @@ for rowid in rowids:
from TestUniversalRowids from TestUniversalRowids
where rowid = :rid""", where rowid = :rid""",
rid = rowid) rid = rowid)
intCol, stringCol, dateCol = cursor.fetchone() int_col, string_col, dateCol = cursor.fetchone()
print("IntCol:", intCol) print("IntCol:", int_col)
print("StringCol:", stringCol) print("StringCol:", string_col)
print("DateCol:", dateCol) print("DateCol:", dateCol)

View File

@ -1,5 +1,5 @@
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
# Copyright (c) 2017, 2019, Oracle and/or its affiliates. All rights reserved. # Copyright (c) 2017, 2020, Oracle and/or its affiliates. All rights reserved.
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -57,93 +57,95 @@ DEFAULT_DRCP_CONNECT_STRING = "localhost/orclpdb1:pooled"
# directly) and then stored so that a value is not requested more than once # directly) and then stored so that a value is not requested more than once
PARAMETERS = {} PARAMETERS = {}
def GetValue(name, label, defaultValue=""): def get_value(name, label, default_value=""):
value = PARAMETERS.get(name) value = PARAMETERS.get(name)
if value is not None: if value is not None:
return value return value
envName = "CX_ORACLE_SAMPLES_" + name env_name = "CX_ORACLE_SAMPLES_" + name
value = os.environ.get(envName) value = os.environ.get(env_name)
if value is None: if value is None:
if defaultValue: if default_value:
label += " [%s]" % defaultValue label += " [%s]" % default_value
label += ": " label += ": "
if defaultValue: if default_value:
value = input(label).strip() value = input(label).strip()
else: else:
value = getpass.getpass(label) value = getpass.getpass(label)
if not value: if not value:
value = defaultValue value = default_value
PARAMETERS[name] = value PARAMETERS[name] = value
return value return value
def GetMainUser(): def get_main_user():
return GetValue("MAIN_USER", "Main User Name", DEFAULT_MAIN_USER) return get_value("MAIN_USER", "Main User Name", DEFAULT_MAIN_USER)
def GetMainPassword(): def get_main_password():
return GetValue("MAIN_PASSWORD", "Password for %s" % GetMainUser()) return get_value("MAIN_PASSWORD", "Password for %s" % get_main_user())
def GetEditionUser(): def get_edition_user():
return GetValue("EDITION_USER", "Edition User Name", DEFAULT_EDITION_USER) return get_value("EDITION_USER", "Edition User Name", DEFAULT_EDITION_USER)
def GetEditionPassword(): def get_edition_password():
return GetValue("EDITION_PASSWORD", "Password for %s" % GetEditionUser()) return get_value("EDITION_PASSWORD",
"Password for %s" % get_edition_user())
def GetEditionName(): def get_edition_name():
return GetValue("EDITION_NAME", "Edition Name", DEFAULT_EDITION_NAME) return get_value("EDITION_NAME", "Edition Name", DEFAULT_EDITION_NAME)
def GetConnectString(): def get_connect_string():
return GetValue("CONNECT_STRING", "Connect String", DEFAULT_CONNECT_STRING) return get_value("CONNECT_STRING", "Connect String",
DEFAULT_CONNECT_STRING)
def GetMainConnectString(password=None): def get_main_connect_string(password=None):
if password is None: if password is None:
password = GetMainPassword() password = get_main_password()
return "%s/%s@%s" % (GetMainUser(), password, GetConnectString()) return "%s/%s@%s" % (get_main_user(), password, get_connect_string())
def GetDrcpConnectString(): def get_drcp_connect_string():
connectString = GetValue("DRCP_CONNECT_STRING", "DRCP Connect String", connectString = get_value("DRCP_CONNECT_STRING", "DRCP Connect String",
DEFAULT_DRCP_CONNECT_STRING) DEFAULT_DRCP_CONNECT_STRING)
return "%s/%s@%s" % (GetMainUser(), GetMainPassword(), connectString) return "%s/%s@%s" % (get_main_user(), get_main_password(), connectString)
def GetEditionConnectString(): def get_edition_connect_string():
return "%s/%s@%s" % \ return "%s/%s@%s" % \
(GetEditionUser(), GetEditionPassword(), GetConnectString()) (get_edition_user(), get_edition_password(), get_connect_string())
def GetAdminConnectString(): def get_admin_connect_string():
adminUser = GetValue("ADMIN_USER", "Administrative user", "admin") admin_user = get_value("ADMIN_USER", "Administrative user", "admin")
adminPassword = GetValue("ADMIN_PASSWORD", "Password for %s" % adminUser) admin_password = get_value("ADMIN_PASSWORD", "Password for %s" % admin_user)
return "%s/%s@%s" % (adminUser, adminPassword, GetConnectString()) return "%s/%s@%s" % (admin_user, admin_password, get_connect_string())
def RunSqlScript(conn, scriptName, **kwargs): def run_sql_script(conn, script_name, **kwargs):
statementParts = [] statement_parts = []
cursor = conn.cursor() cursor = conn.cursor()
replaceValues = [("&" + k + ".", v) for k, v in kwargs.items()] + \ replace_values = [("&" + k + ".", v) for k, v in kwargs.items()] + \
[("&" + 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])) script_dir = os.path.dirname(os.path.abspath(sys.argv[0]))
fileName = os.path.join(scriptDir, "sql", scriptName + "Exec.sql") file_name = os.path.join(script_dir, "sql", script_name + "Exec.sql")
for line in open(fileName): for line in open(file_name):
if line.strip() == "/": if line.strip() == "/":
statement = "".join(statementParts).strip() statement = "".join(statement_parts).strip()
if statement: if statement:
for searchValue, replaceValue in replaceValues: for search_value, replace_value in replace_values:
statement = statement.replace(searchValue, replaceValue) statement = statement.replace(search_value, replace_value)
try: try:
cursor.execute(statement) cursor.execute(statement)
except: except:
print("Failed to execute SQL:", statement) print("Failed to execute SQL:", statement)
raise raise
statementParts = [] statement_parts = []
else: else:
statementParts.append(line) statement_parts.append(line)
cursor.execute(""" cursor.execute("""
select name, type, line, position, text select name, type, line, position, text
from dba_errors from dba_errors
where owner = upper(:owner) where owner = upper(:owner)
order by name, type, line, position""", order by name, type, line, position""",
owner = GetMainUser()) owner = get_main_user())
prevName = prevObjType = None prev_name = prev_obj_type = None
for name, objType, lineNum, position, text in cursor: for name, objType, lineNum, position, text in cursor:
if name != prevName or objType != prevObjType: if name != prev_name or objType != prev_obj_type:
print("%s (%s)" % (name, objType)) print("%s (%s)" % (name, objType))
prevName = name prev_name = name
prevObjType = objType prev_obj_type = objType
print(" %s/%s %s" % (lineNum, position, text)) print(" %s/%s %s" % (lineNum, position, text))