Ruby OCI8 desc table_name - ruby

Thanks for your time!
I use OCI8 to connect Oracle and execute some sql statement.
But when I do as following:
conn = OCI8.new('ci/a#localhost/orcl')
cursor = conn.parse('desc table_name')
cursor.exec
It raised the error:
OCIError: ORA-00900: invalid SQL statement
I've asked some DBA and they told me that desc is Data Definition Language (DDL) , which is not a normal SQL, and probably that's what caused the issue.
I use Ruby as my scripting language. How could I solve this problem?

desc is not DDL. It is a sqlplus command.
Use OCI8#describe_table or dictionary views as follows:
conn.describe_table('TABLE_NAME').columns.each do |col|
puts format('%-30s %s', col.name, col.data_type_string)
end
or
conn.exec("select column_name, data_type
from all_tab_columns
where owner = 'OWNER_NAME'
and table_name = 'TABLE_NAME'
order by column_id") do |row|
puts format('%-30s %s', row[0], row[1])
end
The former works for tables, views and synonyms. The latter works only for tables.

Related

How do I search for all the columns/field names starting with "XYZ" in Azure Databricks

I would like to do a big search on all field/columns names that contain "XYZ".
I tried below sql but it's giving me an error.
SELECT
table_name
,column_name
FROM information_schema.columns
WHERE column_name like '%account%'
order by table_name, column_name
ERROR states "Table or view not found: information_schema.columns; line 4, pos 5"
information_schema.columns is not supported in Databricks SQL. There are no in-built views available to get the complete details of tables along with columns. There is SHOW TABLES (database needs to be given) and SHOW COLUMNS (table name needs to be given).
You might have to use Pyspark capabilities to get the required result. First use the following code to get the details of all tables and respective columns:
db_tables = spark.sql(f"SHOW TABLES in default")
from pyspark.sql.functions import *
final_df = None
for row in db_tables.collect():
if(final_df is None):
final_df = spark.sql(f"DESCRIBE TABLE {row.database}.{row.tableName}")\
.withColumn('database',lit(f'{row.database}'))\
.withColumn('tablename',lit(f'{row.tableName}'))\
.select('database','tablename','col_name')
else:
final_df = final_df.union(spark.sql(f"DESCRIBE TABLE {row.database}.{row.tableName}")\
.withColumn('database',lit(f'{row.database}'))\
.withColumn('tablename',lit(f'{row.tableName}'))\
.select('database','tablename','col_name'))
#display(final_df)
final_df.createOrReplaceTempView('req')
Create a view and then apply the following query:
%sql
SELECT tablename,col_name FROM req WHERE col_name like '%id%' order by tablename, col_name

Count of rows from all views in Oracle with a condition

I am trying to get count of all rows from views in oracle schema and my code is working fine. But when i try to add a condition like where actv_ind = 'Y', i am unable to get it working. Any suggestions on how to modify the code to make it working?
SELECT view_name,
TO_NUMBER(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) cnt from '||owner||'.'||view_name||
'where'||view_name||'.'||'actv_ind= Y')),'/ROWSET/ROW/CNT')) as VIEW_CNT
FROM all_views
WHERE owner = 'ABC' AND view_name not in ('LINK$')
I am getting the error ACTV_IND : Invalid Identifier.
The error messages from DBMS_XMLGEN are not very helpful so you need to be very careful with the syntax of the SQL statement. Add a space before and after the where, and add quotation marks around the Y:
SELECT view_name,
TO_NUMBER(extractvalue(xmltype(dbms_xmlgen.getxml('select count(*) cnt from '||owner||'.'||view_name||
' where '||view_name||'.'||'actv_ind= ''Y''')),'/ROWSET/ROW/CNT')) as VIEW_CNT
FROM all_views
WHERE owner = 'ABC' AND view_name not in ('LINK$');
The query still assumes that every view contains the column ACTV_IND. If that is not true, you might want to base the query off of DBA_TAB_COLUMNS WHERE COLUMN_NAME = 'ACTV_IND'.
Here's a simple sample schema I used for testing:
create user abc identified by abc;
create or replace view abc.view1 as select 1 id, 'Y' actv_ind from dual;
create or replace view abc.view2 as select 2 id, 'N' actv_ind from dual;

postgres, database with schema in ruby code

I connected to postgres database from ruby with no problem, but when they added schema , I got confused and go error , here is the code I am trying to run :
require 'pg'
#pg_conn = PGconn.connect("xxxxxxx.us-gov-west-1.rds.amazonaws.com", 5432, '', '', "BRCArchive", "yyyy", "zzzz")
count = #pg_conn.exec('SELECT COUNT(*) FROM "brcmanager.Agency"')
puts count
I got this error :
Called from brc_migration2.rb:7:in `<main>'
brc_migration2.rb:9:in `exec': ERROR: relation "brcmanager.Agency" does not exist (PG::UndefinedTable)
LINE 1: SELECT COUNT(*) FROM "brcmanager.Agency"
^
from brc_migration2.rb:9:in `<main>'
Thanks,
#pg_conn.exec("set search_path=brcmanager;")
and then
count = #pg_conn.exec('SELECT COUNT(*) FROM Agency')
The error tells you what's wrong. The table brcmanager.Agency does not exist in that database, perhaps you misspelled it?
You can see what tables exist in that database by running this SQL:
SELECT * FROM information_schema.tables WHERE table_schema = 'information_schema'

Dropping tables in sqlite3 in ruby

I am trying to drop a table from a database. However I keep getting an error. The code and the error message are below. Appreciate your help. The table csv_07-15-2014_10-00 is present in the DB.
require 'win32ole'
require 'sqlite3'
DB_NAME = 'excel.db'
db = SQLite3::Database.new(DB_NAME)
sqlQuery = "SELECT * FROM sqlite_master WHERE type = 'table'"
puts db.execute(sqlQuery )
sqlQuery = "DROP TABLE csv_07-15-2014_10-00"
puts sqlQuery
puts db.execute(sqlQuery)
Error message is below:
C:/Ruby193/lib/ruby/gems/1.9.1/gems/sqlite3-1.3.9-x86-mingw32/lib/sqlite3/databa
se.rb:91:in `initialize': near "-": syntax error (SQLite3::SQLException)
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/sqlite3-1.3.9-x86-mingw32/lib/s
qlite3/database.rb:91:in `new'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/sqlite3-1.3.9-x86-mingw32/lib/s
qlite3/database.rb:91:in `prepare'
from C:/Ruby193/lib/ruby/gems/1.9.1/gems/sqlite3-1.3.9-x86-mingw32/lib/s
qlite3/database.rb:134:in `execute'
from sqldroptable.rb:19:in `<main>'
PUT Statement output is below:
table
csv_07-15-2014_10-00
csv_07-15-2014_10-00
2
CREATE TABLE [csv_07-15-2014_10-00]
( mineId,prod_year,prod_qtr,subunit_cd,subunit,qtr_hrs,coal_prod,avg_emp_cnt )
table
csv_07-14-2014_22-30
csv_07-14-2014_22-30
8
CREATE TABLE [csv_07-14-2014_22-30]
( mineId,prod_year,prod_qtr,subunit_cd,subunit,qtr_hrs,coal_prod,avg_emp_cnt )
table
csv_07-14-2014_22-29
csv_07-14-2014_22-29
9
CREATE TABLE [csv_07-14-2014_22-29]
( mineId,prod_year,prod_qtr,subunit_cd,subunit,qtr_hrs,coal_prod,avg_emp_cnt )
DROP TABLE csv_07-15-2014_10-00 FROM sqlite_maste
r
You have SQL exception i think problem in escaping query try this:
sqlQuery = "DROP TABLE \"csv_07-15-2014_10-00\""
In SQL, - is the subtraction operator, which does not make sense in a DROP TABLE statement.
If you have special characters in an identifier, you must quote it:
sqlQuery = "DROP TABLE [csv_07-15-2014_10-00]"
or
sqlQuery = "DROP TABLE \"csv_07-15-2014_10-00\""
or
sqlQuery = "DROP TABLE `csv_07-15-2014_10-00`"

Query Oracle for running sql and value of bind variables

If I run the SQL in Fig. 1 below, it may return something like this:
Select fname, lname from name_tbl where nam_key = :key
Without using some fancy DBA trace utility, how can I query an Oracle system table to find the value of the bind variable “:key”?
Figure 1. - List the current running sql statement.
select sid, username, sql_text
from v$session,
v$sqltext
where sql_address = address
and sql_hash_value = hash_value
order by sid, piece;
select name, value_string
from v$sql_bind_capture
where sql_id = your_query_id
Upd. or, of course:
select sql_id, value_string
from v$sql_bind_capture
where name = ':key'

Resources