SQL syntax error while trying to execute script with multiple CREATE VIEW statements via EntityManager - sql

I would like to create a bunch of SQL views at my Quarkus application startup and I wrote
#Inject
EntityManager em;
public void exec(... sql) {
logger.info("EXECUTING " ...);
sql = "BEGIN\n" + sql + "\nEND";
Query q = em.createNativeQuery(sql);
q.executeUpdate();
}
And my SQL file is following:
CREATE OR REPLACE VIEW My_view_ex AS
SELECT cc.*, If(cc.beautifulName IS NULL, cc.name, cc.beautifulName) canonName FROM My_table cc;
CREATE OR REPLACE VIEW MyView2 AS
...
Unfortunately, it throws exception, saying
java.sql.SQLException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'CREATE OR REPLACE VIEW My_view_ex AS
SELECT cc.*, If(cc.beautifulName IS NU...' at line 2
If I copy paste the content of sql varible to database client and execute it, then it works, i.e. there is no actually syntax error. Probably it dislikes multiple queries or line ends or something.
What else can be suggested?

Related

Access violation at address 04FD6CC2 in module 'dbxora.dll'. Read of address 00000004

I have created DELPHI database application which will use DBX TSQLConnection component to connect to Oracle database (19c version).
I'm getting access violation error , When i call oracle listagg function (SQLQuery1.open --in this line).
When i debugged , i got the error in below object file,
FileName : Data.DBXDynalink.pas
Function : function TDBXDynalinkReader.DerivedNext: Boolean;
Error Line : DBXResult := FMethodTable.FDBXReader_Next(FReaderHandle);
Actual Error : Access violation at address 04FD6CC2 in module 'dbxora.dll'. Read of address 00000004
Below is my code ,
...SQLQuery1 initialization....
SQLQuery1.CommandText := Trim(memoSQLText.Lines.Text); // Assigning query
SQLQuery1.Open; // Exactly on this line i'm getting error
if SQLQuery1.RecordCount > 0 then
....Do something here....
Note : Same query is executing in other versions which are all below to Oracle version 19C (19.3)
IDE version used for application development : DELPHI XE3 (i have checked with DELPHI 10.1 Berlin also)
DB version : Oracle 19C (19.3)
Steps to reproduce :
// 1.Execute below queries in order to create testing data ,
create table myuserlist(myuser varchar2(10));
Insert into myuserlist(myuser) values('karthik');
Insert into myuserlist(myuser) values('aarush');
Insert into myuserlist(myuser) values('yuvan');
// 2.Try to open the below mentioned query using TSQLConnection and TSQLQuery
select listagg(a.myuser, ', ') within group (order by a.myuser) as myusernames from myuserlist a
Sample project is available in the GitHub,
https://github.com/yuvankarthik/DELPHI-DemoOracleConnect.git
Help me to resolve this issue.

how to run multiple sql statements in airflow jinja template using jdbc hook

Trying to run a hive sql using jdbchook and jinja template through airflow. Template works fine for a single sql statement but throws a parsing error with multiple statements.
DAG
p1 = JdbcOperator(
task_id=DAG_NAME+'_create',
jdbc_conn_id='big_data_hive',
sql='/mysql_template.sql',
params={'env': ENVIRON},
autocommit=True,
dag=dag)
Template
create table {{params.env}}_fct.hive_test_templated
(cookie_id string
,sesn_id string
,load_dt string)
;
INSERT INTO {{params.env}}_fct.hive_test_templated
select* from {{params.env}}_fct.hive_test
;
Error: org.apache.hive.service.cli.HiveSQLException: Error while compiling statement: FAILED: ParseException line 7:0 missing EOF at ';' near ')'
The template queries works fine when I run it in Hue.
tobi is correct, the easiest way to do this is to parse your SQL statement into a list of SQL's and execute them sequentially.
The way that I do this is by using the sqlparse python library to split the string into a list of SQL statements and then pass them down to the hook (inherits dbapi hook) - the dbapi base class accepts a list of SQL statements and executes the sequentially, this could easily be implemented in the hive hook too. In the following example my "CustomSnoqflakeHook" inherits from the dbapi hook and the run method in the dbapi hook accpets a list of SQL statements :
hook = hooks.CustomSnowflakeHook(snowflake_conn_id=self.snowflake_conn_id)
sql = sqlparse.split(sqlparse.format(self.sql, strip_comments=True))
hook.run(
sql,
autocommit=self.autocommit,
parameters=self.parameters)
From the dbapi hook:
def run(self, sql, autocommit=False, parameters=None):
"""
Runs a command or a list of commands. Pass a list of sql
statements to the sql parameter to get them to execute
sequentially
:param sql: the sql statement to be executed (str) or a list of
sql statements to execute
:type sql: str or list
:param autocommit: What to set the connection's autocommit setting to
before executing the query.
:type autocommit: bool
:param parameters: The parameters to render the SQL query with.
:type parameters: mapping or iterable
"""
if isinstance(sql, basestring):
sql = [sql]
with closing(self.get_conn()) as conn:
if self.supports_autocommit:
self.set_autocommit(conn, autocommit)
with closing(conn.cursor()) as cur:
for s in sql:
if sys.version_info[0] < 3:
s = s.encode('utf-8')
self.log.info(s)
if parameters is not None:
cur.execute(s, parameters)
else:
cur.execute(s)
if not getattr(conn, 'autocommit', False):
conn.commit()
It seems to me that Hue parses the statement differently. Sometimes there are statement separators implemented which allow this to happen.
Airflow seems not to have those separators.
So the easiest way would be to separate the two statements and execute those statements in two separate tasks.

java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist error message in netbeans 8.0.1

when i was trying to delete all records form Oracle database using the following code i got this exception,
QUERYY:: delete from DMUSER.CAMERA_DATA1
java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not exist
Actually here I wanted to create a data mining application using oracle SQL developer and the netbeans IDE. So my workflow is looks like as follow in oracle SQL developer,
The code part that I have used to delete a record from database as follows,
public void deleteData()throws SQLException {
Statement stmt = null;
String query = "delete from DMUSER.CAMERA_DATA1";
System.out.println("QUERYY:: " + query);
try {
stmt = getConnection().createStatement();
int rs = stmt.executeUpdate(query);
if (rs > 0) {
System.out.println("<-------------------Record Deleted--------------->");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (stmt != null) {
stmt.close();
}
}
}
I'm very new to the environment and searched many related questions even in stack but couldn't find exact answer which makes my work successful. Please help me to solve this.
QUERYY:: delete from DMUSER.CAMERA_DATA1
java.sql.SQLSyntaxErrorException: ORA-00942: table or view does not
exist
You need to check, if CAMERA_DATA1 table/view exists in DMUSER schema or not.
Try connecting to same database and schema and check, if table exist or not. If not, then you need to create this table/view in same schema.
Referring to your screenshot provided, I can see CAMERA_DATA table instead of CAMERA_DATA1. So, you can either correct the SQL query to below
String query = "delete from DMUSER.CAMERA_DATA";

Initialize / activate SQL prior to GET DIAGNOSTICS

I have two service programs: mySrvPgm and myErr
mySrvPgm has a procedure which contains:
/free
...
exec sql INSERT INTO TABLE VALUES(:RECORD_FMT);
if sqlError() = *ON;
//handle error
endif;
...
/end-free
myErr has a procedure sqlError:
/free
exec sql GET DIAGNOSTICS CONDITION 1
:state = RETURNED_SQLSTATE;
...
/end-free
Background info: I am using XMLSERVICE to call the given procedure in mySrvPgm from PHP. I am not using a persistent connection. myErr is bound-by-reference via a binding directory used by mySrvPgm. Its activation is set to *IMMED, its activation group is set to *CALLER.
The problem: Assume there is an error on the INSERT statement in mySvrPgm. The first time sqlError() is called it will return SQLSTATE 00000 despite the error. All subsequent calls to sqlError() return the expected SQLSTATE.
A workaround: I added a procedure to myErr called initSQL:
/free
exec sql SET SCHEMA MYLIB;
/end-free
If I call initSQL() before the INSERT statement in mySrvPgm, sqlError() functions correctly. It doesn't have to be SET SCHEMA, it can be another GET DIAGNOSTICS statement. However, if it does not contain an executable SQL statement it does not help.
The question: I believe the myErr service program is activating properly and has the correct scope, but I am wondering if there is something more I need to do to activate the SQL part of it. Is there some way to set it up so SQL auto-initializes when the service program is activated, or do I have to execute an unneeded SQL statement in order to get it started?
There is some more background information available here.
Thank you for reading.
What version an release of the OS? Are you upto date on PTFs?
Honestly, seems to me that it's possibly a bug. Or the manual(s) need clarification.. I'd open a PMR.

Yii CDbException.. invalid input syntax for integer: "1,075"

I started receiving this error from a production site since this morning and I'm wondering why I don't get the same in UAT or the developer environment..
Is any one familiar with an error like this ?
CDbException
Description
CDbCommand failed to execute the SQL statement: SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: "1,076"
Source File
C:\inetpub\wwwroot\framework1.0\db\CDbCommand.php(372)
00360: }
00361:
00362: if($this->_connection->enableProfiling)
00363: Yii::endProfile('system.db.CDbCommand.query('.$this->getText().')','system.db.CDbCommand.query');
00364:
00365: return $result;
00366: }
00367: catch(Exception $e)
00368: {
00369: if($this->_connection->enableProfiling)
00370: Yii::endProfile('system.db.CDbCommand.query('.$this->getText().')','system.db.CDbCommand.query');
00371: Yii::log('Error in querying SQL: '.$this->getText().$par,CLogger::LEVEL_ERROR,'system.db.CDbCommand');
00372: throw new CDbException(Yii::t('yii','CDbCommand failed to execute the SQL statement: {error}',
00373: array('{error}'=>$e->getMessage())));
00374: }
00375: }
00376: }
Attached a screenshot too.. the application is based on yii framework and postgress database.
Quick reply is highly appreciated.
The issue was actually because used number_format() function to a primary key and later in a code section it inputs the formatted number to search query.. i.e select * from user where id = 1,075 (instead of id = 1075)
Changing the number_format() function to apply only on selected areas worked.