UPDATING an IMAGE column in Sybase with PREPARED statement fails - sap-ase

This is with ASE 15.7 and ESQL/C. Updating a row in a CURSOR with a prepared statement:
EXEC SQL BEGIN DECLARE SECTION;
CS_IMAGE image[512];
EXEC SQL END DECLARE SECTION;
strcpy(image, "foo");
EXEC SQL PREPARE updt FROM "UPDATE image_test SET nettodaten = ? WHERE CURRENT OF hc_image_test";
EXEC SQL EXECUTE updt USING :image;
fails with the message from ASE:
** SQLCODE=(-201)
** ASE Error
** Procedure *sq1625128094_1900377684ss* expects parameter
Invalid pointer param number 4, pointer value 0x(nil)
, which was not supplied.
What could be the reason for this?
Update 1
I modified the ESQL/C code a bit so it looks like this:
strcpy(anweisung, "UPDATE image_test SET katkey = ?, nettodaten = ? WHERE CURRENT OF hc_image_test");
EXEC SQL PREPARE updt FROM :anweisung;
EXEC SQL EXECUTE updt USING :key, :blobfld;
EXEC SQL CLOSE hc_image_test;
The error remains the same as above. But a look into the produced C-code by CPRE shows an interesting detail:
/*
** SQL STATEMENT: 17
** EXEC SQL EXECUTE updt USING :key, :blobfld;
*/
{
_SQL_CT_HANDLES * _sql;
_sqlinitctx(&_sql, CS_CURRENT_VERSION, CS_TRUE, &sqlca, (long
*)NULL, (CS_CHAR *)NULL);
if (_sql != (_SQL_CT_HANDLES *) NULL)
{
_sql->stmtData.persistent = CS_FALSE;
_sql->stmttype = SQL_EXECUTE;
_sql->connName.lnlen = CS_UNUSED;
_sql->stmtName.fnlen = 4;
strcpy(_sql->stmtName.first_name, "updt");
if ((_sql->retcode = _sqlprolog(_sql)) == CS_SUCCEED)
{
_sql->retcode = ct_dynamic(_sql->conn.command,
CS_EXECUTE, "updt", 4, NULL, CS_UNUSED);
if (_sql->retcode == CS_SUCCEED)
{
_sql->dfmtCS_INT_TYPE.count = 0;
_sql->dfmtCS_INT_TYPE.status = CS_INPUTVALUE;
_sql->retcode = ct_param(_sql->conn.command,
&_sql->dfmtCS_INT_TYPE, &key, (CS_INT)
CS_UNUSED, (CS_SMALLINT) 0);
_sql->dfmtCS_INT_TYPE.status = 0;
}
_sql->retcode = ct_send(_sql->conn.command);
_sql->hastate = (_sql->retcode == CS_RET_HAFAILOVER);
_sql->retcode = _sqlResults(_sql);
_sql->retcode = _sqlepilog(_sql);
}
if (sqlca.sqlcode < 0)
{
error_handler();
}
As one can see above, a pointer to the host variable CS_INT :key is placed with a call to ct_param() into the internal structures, but not any reference to the host variable CS_IMAGE :blobfld. And that's why ASE is complaining with a missing param value because it sees two question marks ? in the prepared UPDATE statement. This looks to me somehow as a bug in the CPRE compiler and not in ASE itself.

I have contacted through our maintenance contract the company SAP (the issue number there is 390674 / 2018) and some engineer is looking into this CPRE issue...
For the moment, I'm adding to the C-code produce by CPRE, short before the ct_send() call, the following lines of code to add the missing reference to the IMAGE column:
/* additional code for host var :blobfld */
if (_sql->retcode == CS_SUCCEED)
{
_sql->dfmtCS_IMAGE_TYPE.count = 0;
_sql->dfmtCS_IMAGE_TYPE.maxlength = (CS_INT) 65535;
_sql->dfmtCS_IMAGE_TYPE.format = CS_FMT_UNUSED;
_sql->dfmtCS_IMAGE_TYPE.status = CS_INPUTVALUE;
_sql->retcode = ct_param(_sql->conn.command,
&_sql->dfmtCS_IMAGE_TYPE, blobfld, (CS_INT) ImageLengthField,
(CS_SMALLINT) 0);
_sql->dfmtCS_IMAGE_TYPE.status = 0;
}
/* end of additional code for host var :blobfld */
_sql->retcode = ct_send(_sql->conn.command);
...
And all works fine.

Related

OMNotebook Error: Class dev not found in scope (looking for a function or record)

I have modified the van der Pol example from DrModelica with the following changes:
model FPStirling "Free Piston Stirling engine model"
Real x(start = 1,fixed = true);
Real v(start = 1,fixed = true);
Real T(start = 1,fixed = true);
equation
der(x) = v;
dev(v) = T/x-1;
dev(T) = 1 - x;
end FPStirling;
It evaluates and returns: {FPStirling}
Then I run: simulate(FPStirling, startTime=0, stopTime=25 )
But I get the output:
record SimulationResult
resultFile = "",
messages = "Failed to build model: FPStirling"
end SimulationResult;
OMC-ERROR:
"[7:3-7:17] Error: Class dev not found in scope FPStirling (looking for a function or record).
Error: Error occurred while flattening model FPStirling
"
Could it be a path problem?
Do you really have a function dev defined somewhere? Or maybe its a typo for der.
Adeel.

Python-MySQL : removing single quotes around variable values in query while running db.execute(str, vars)

I am running this code
def details(self, dbsettings, payload):
res = None
with UseDatabase(dbsettings) as db:
sql = "select * from %(tablename)s where userid = %(userid)s"
result = db.run_query_vals(sql, payload)
res = result.fetchall()
return res
but get an error
SQLError: 1064 (42000): 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 ''statuser' where userid = '14'' at line 1
The arguments being passed are :
sql = "select * from %(tablename)s where userid = %(userid)s"
payload = {'tablename' : 'statuser', 'userid' : 14}
As far as I understand, the query being passed to MySQL is along the lines of
select * from 'statuser' where userid = '14'
which is where I get the error; the tablename isnt supposed to be enclosed in quotes. How do I have the name included without the quotes/make them backquotes?
(I don't want to hard-code the table name - this is a variable and is initialised according to different parameters during class creation). Any help here?
You can use the .format() from string in python:
def details(self, dbsettings, payload):
res = None
with UseDatabase(dbsettings) as db:
sql = "select * from {tablename} where userid = {userid}"
sql = sql.format(**payload)
# result = db.run_query_vals(sql, payload) # Method to run query
res = result.fetchall()
return res
I encountered the same problem in pymysql and have figured out a solution:
rewrite the escape method in class 'pymysql.connections.Connection', which obviously adds "'" arround your string.
don't know whether it will help in your case, just sharing a possible way
similiar question: How to remove extra quotes in pymysql
Here's my code:
from pymysql.connections import Connection, converters
class MyConnect(Connection):
def escape(self, obj, mapping=None):
"""Escape whatever value you pass to it.
Non-standard, for internal use; do not use this in your applications.
"""
if isinstance(obj, str):
return self.escape_string(obj) # by default, it is :return "'" + self.escape_string(obj) + "'"
if isinstance(obj, (bytes, bytearray)):
ret = self._quote_bytes(obj)
if self._binary_prefix:
ret = "_binary" + ret
return ret
return converters.escape_item(obj, self.charset, mapping=mapping)
config = {'host':'', 'user':'', ...}
conn = MyConnect(**config)
cur = conn.cursor()

Perl: String to anonymous array?

SOLVED ALREADY --> See edit 7
At this moment I'm fairly new on Perl, and trying to modify part of an existing page (in Wonderdesk).
The way the page works, is that it gets the information from the GET url and parses it to an SQL query.
Since this is part of a much larger system, I'm not able to modify the coding around it, and have to solve it in this script.
A working test I performed:
$input->{help_id} = ['33450','31976'];
When running this, the query that is being build returns something as
select * from table where help_id in(33450,31976)
The part of my code that does not work as expected:
my $callIDs = '33450,31450';
my #callIDs = split(/,/,$callIDs);
my $callIDsearch = \#callIDs;
$input->{help_id} = $callIDsearch;
When running this, the query that is being build returns something as
select * from table where help_id = '33450,31976'
I've tried to debug it, and used Data::Dumper to get the result of $callIDsearch, which appears as [33450, 31450] in my browser.
Can someone give me a hint on how to transform from '123,456' into ['123', '456']?
With kind regards,
Marcel
--===--
Edit:
As requested, minimal code piece that works:
$input->{help_id} = ['123','456']
Code that does not work:
$str = '123,456';
#ids = split(/,/,$str);
$input->{help_id} = \#ids;
--===--
Edit 2:
Source of the question:
The following part of the code is responsible for getting the correct information from the database:
my $input = $IN->get_hash;
my $db = $DB->table('help_desk');
foreach (keys %$input){
if (/^corr/ and !/-opt$/ and $input->{$_} or $input->{keyword}){
$db = $DB->table('help_desk','correspondence');
$input->{rs} = 'DISTINCT help_id,help_name,help_email,help_datetime,help_subject,help_website,help_category,
help_priority,help_status,help_emergency_flag,help_cus_id_fk,help_tech,help_attach';
$input->{left_join} = 1;
last;
}
}
# Do the search
my $sth = $db->query_sth($input);
my $hits = $db->hits;
Now instead of being able to provide a single parameter help_id, I want to be able to provide multiple parameters.
--===--
Edit 3:
query_sth is either of the following two, have not been able to find it out yet:
$COMPILE{query} = __LINE__ . <<'END_OF_SUB';
sub query {
# -----------------------------------------------------------
# $obj->query($HASH or $CGI);
# ----------------------------
# Performs a query based on the options in the hash.
# $HASH can be a hash ref, hash or CGI object.
#
# Returns the result of a query as fetchall_arrayref.
#
my $self = shift;
my $sth = $self->_query(#_) or return;
return $sth->fetchall_arrayref;
}
END_OF_SUB
$COMPILE{query_sth} = __LINE__ . <<'END_OF_SUB';
sub query_sth {
# -----------------------------------------------------------
# $obj->query_sth($HASH or $CGI);
# --------------------------------
# Same as query but returns the sth object.
#
shift->_query(#_)
}
END_OF_SUB
Or
$COMPILE{query} = __LINE__ . <<'END_OF_SUB';
sub query {
# -------------------------------------------------------------------
# Just performs the query and returns a fetchall.
#
return shift->_query(#_)->fetchall_arrayref;
}
END_OF_SUB
$COMPILE{query_sth} = __LINE__ . <<'END_OF_SUB';
sub query_sth {
# -------------------------------------------------------------------
# Just performs the query and returns an active sth.
#
return shift->_query(#_);
}
END_OF_SUB
--===--
Edit 4: _query
$COMPILE{_query} = __LINE__ . <<'END_OF_SUB';
sub _query {
# -------------------------------------------------------------------
# Parses the input, and runs a select based on input.
#
my $self = shift;
my $opts = $self->common_param(#_) or return $self->fatal(BADARGS => 'Usage: $obj->insert(HASH or HASH_REF or CGI) only.');
$self->name or return $self->fatal('NOTABLE');
# Clear errors.
$self->{_error} = [];
# Strip out values that are empty or blank (as query is generally derived from
# cgi input).
my %input = map { $_ => $opts->{$_} } grep { defined $opts->{$_} and $opts->{$_} !~ /^\s*$/ } keys %$opts;
$opts = \%input;
# If build_query_cond returns a GT::SQL::Search object, then we are done.
my $cond = $self->build_query_cond($opts, $self->{schema}->{cols});
if ( ( ref $cond ) =~ /(?:DBI::st|::STH)$/i ) {
return $cond;
}
# If we have a callback, then we get all the results as a hash, send them
# to the callback, and then do the regular query on the remaining set.
if (defined $opts->{callback} and (ref $opts->{callback} eq 'CODE')) {
my $pk = $self->{schema}->{pk}->[0];
my $sth = $self->select($pk, $cond) or return;
my %res = map { $_ => 1 } $sth->fetchall_list;
my $new_results = $opts->{callback}->($self, \%res);
$cond = GT::SQL::Condition->new($pk, 'IN', [keys %$new_results]);
}
# Set the limit clause, defaults to 25, set to -1 for none.
my $in = $self->_get_search_opts($opts);
my $offset = ($in->{nh} - 1) * $in->{mh};
$self->select_options("ORDER BY $in->{sb} $in->{so}") if ($in->{sb});
$self->select_options("LIMIT $in->{mh} OFFSET $offset") unless $in->{mh} == -1;
# Now do the select.
my #sel = ();
if ($cond) { push #sel, $cond }
if ($opts->{rs} and $cond) { push #sel, $opts->{rs} }
my $sth = $self->select(#sel) or return;
return $sth;
}
END_OF_SUB
--===--
Edit 5: I've uploaded the SQL module that is used:
https://www.dropbox.com/s/yz0bq8ch8kdgyl6/SQL.zip
--===--
Edit 6:
On request, the dumps (trimmed to only include the sections for help_id):
The result of the modification in Base.pm for the non-working code:
$VAR1 = [
33450,
31450
];
The result of the modification in Condition.pm for the non-working code:
$VAR1 = [
"help_id",
"IN",
[
33450,
31450
]
];
$VAR1 = [
"cus_username",
"=",
"Someone"
];
$VAR1 = [
"help_id",
"=",
"33450,31450"
];
The result for the modification in Base.pm for the working code:
$VAR1 = [
33450,
31976
];
The result for the modification in Condition.pm for the working code:
$VAR1 = [
"help_id",
"IN",
[
33450,
31976
]
];
It looks as if the value gets changed afterwards somehow :S
All I changed for the working/non-working code was to replace:
$input->{help_id} = ['33450','31976'];
With:
$input->{help_id} = [ split(/,/,'33450,31450') ];
--===--
Edit 7:
After reading all the tips, I decided to start over and found that by writing some logs to files, I could break down into the issue with more details.
I'm still not sure why, but it now works, using the same methods as before. I think it's a typo/glitch/bug in my code somewhere..
Sorry to have bothered you all, but I still recommend the points to go to amon due to his tips providing the breakthrough.
I don't have an answer, but I have found a few critical points where we need to know what is going on.
In build_query_cond (Base.pm line 528), an array argument will be transformed into an key in (...) relation:
if (ref($opts->{$field}) eq 'ARRAY' ) {
my $add = [];
for ( #{$opts->{$field}} ) {
next if !defined( $_ ) or !length( $_ ) or !/\S/;
push #$add, $_;
}
if ( #$add ) {
push #ins, [$field, 'IN', $add];
}
}
Interesting bit in sql (Condition.pm line 181). Even if there is an arrayref, an IN test will be simplified to an = test if it contains only a single element.
if (uc $op eq 'IN' || $op eq '=' and ref $val eq 'ARRAY') {
if (#$val > 1) {
$op = 'IN';
$val = '('
. join(',' => map !length || /\D/ ? quote($_) : $_, #$val)
. ')';
}
elsif (#$val == 0) {
($col, $op, $val) = (qw(1 = 0));
}
else {
$op = '=';
$val = quote($val->[0]);
}
push #output, "$col $op $val";
}
Before these two conditions, it would be interesting to insert the following code:
Carp::cluck(Data::Dumper::Dump(...));
where ... is $opts->{$field} in the first snippet or $cond in the second snippet. The resulting stack trace would allow us to find all subroutines which could have modified the value. For this to work, the following code has to be placed in your main script before starting the query:
use Carp ();
use Data::Dumper;
$Data::Dumper::Useqq = 1; # escape special characters
Once the code has been modified like this, run both the working and not-working code, and print out the resulting query with
print Dumper($result);
So for each of your code snippets, we should get two stack traces and one resulting SQL query.
A shot in the dark... there's a temporary array #callIDs created by this code:
my #callIDs = split(/,/,$callIDs);
my $callIDsearch = \#callIDs;
$input->{help_id} = $callIDsearch;
If some other part of your code modifies #callIDs, even after it's been assigned to $input->{help_id}, that could cause problems. Of course the fact that it's a lexical (my) variable means that any such changes to #callIDs are probably "nearby".
You could eliminate the named temporary array by doing the split like this:
$input->{help_id} = [ split(/,/,$callIDs) ];
I'm not sure I understand exactly why this is happening. It seems that your query builder needs an arrayref of strings. You can use map to do that
my $callIDs = '33450,31450';
my #callIDs = map {$_*1} split(/,/,$callIDs);
$input->{help_id} = \#callIDs;
This code should work
my $callIDs = '33450,31450';
$input->{help_id} = [split ",", $callIDs];
If your code somehow detect your data is number you can use
my $callIDs = '33450,31450';
$input->{help_id} = [map 0+$_, split ',', $callIDs];
If it somehow become number and you need string instead which should not in this case but advice for future work:
my $callIDs = '33450,31450';
$input->{help_id} = [map ''.$_, split ',', $callIDs];

CS Script not working

I have setup a dynamic script (using CSScriptLibrary) in my C# program as follows:
string sqlReturnValue= cmd.ExecuteQuery();;
dynamic script = CSScript.Evaluator
.LoadCode(#"using System;
public class Script
{
string GetValue()
{
return " + sqlReturnValue + #";
}
}");
output = script.GetValue();
sqlReturnValue is a string that I get back from a SQL query similar to this:
"Salaried Grade 1".Substring(0, 7) == "Salaried") ? "CLA_SH_S" : "CLA_SH_H";
When I try to execute this the dynamic code gives me errors of "Unexpected symbol )', expecting ;'" & "Unexpected symbol :', expecting ;'"
How can I write this dynamic script such that it evaluates the ternary correctly?
IN case someone finds this useful, I was able to get this working as follows:
string sqlReturnValue = cmd.ExecuteQuery();
// Use CSScript to evaluate the test string returned from the SQL Query
var Product = CSScript.Evaluator
.CreateDelegate(#"string Product()
{
return " + sqlReturnValue + #";
}");
output = (string)Product();

What is the maximum number of parameters I can use in a subsonic 2.1+ 'IN' statment?

I think i am hitting a limit. I have two IN statements in the SQL generated by subsonic. Or am I hitting the varchar ( 8000 ) limit?
When I send i fewer parameters, the statement returns results, when I send in more, the result set comes back blank.
Below is what I am catching in SQL Profiler:
exec sp_executesql N'/* GetDataSet() */
SELECT
[dbo].[QuoteDBAll].[quote_id],
[dbo].[conn_quote_result].[product_category_name],
part_number,
quote_result_special_price * ( quote_result_quantity + quote_result_quantity_spare) AS Total,
company_name
FROM [dbo].[QuoteDBAll]
INNER JOIN [dbo].[conn_quote_result]
ON [dbo].[QuoteDBAll].[quote_number] = [dbo].[conn_quote_result].[quote_number]
INNER JOIN [dbo].[conn_company]
ON [dbo].[QuoteDBAll].[company_id] = [dbo].[conn_company].[company_id]
GROUP BY [dbo].[QuoteDBAll].[quote_id],
[dbo].[conn_quote_result].[product_category_name],
[dbo].[conn_quote_result].[part_number],
[dbo].[conn_quote_result].[quote_result_quantity],
[dbo].[conn_quote_result].[quote_result_quantity_spare],
[dbo].[conn_quote_result].[quote_result_special_price],
[dbo].[QuoteDBAll].[quote_status_id],
company_name
HAVING (quote_status_id = #quote_status_id0)
AND (company_name IN
(#in1,#in2,#in3,#in4,#in5,#in6,#in7,#in8,#in9,#in10,
#in11,#in12,#in13,#in14,#in15,#in16,#in17,#in18,#in19,#in20,
#in21,#in22,#in23,#in24,#in25,#in26,#in27,#in28,#in29,#in30,#in31))
AND ([dbo].[conn_quote_result].[product_category_name] IN
(#in1,#in2,#in3,#in4,#in5,#in6,#in7,#in8,#in9,#in10,
#in11,#in12,#in13,#in14,#in15,#in16,#in17,#in18,#in19,#in20,
#in21,#in22,#in23,#in24,#in25,#in26,#in27,#in28,#in29,#in30,
#in31,#in32,#in33,#in34,#in35,#in36,#in37,#in38))',
N'#quote_status_id0 varchar(1),### varchar(8000),#in1 varchar(15),#in2 varchar(22),
#in3 varchar(21),#in4 varchar(13),#in5 varchar(5),#in6 varchar(6),#in7 varchar(13),
#in8 varchar(25),#in9 varchar(8),#in10 varchar(14),#in11 varchar(9),#in12 varchar(11),
#in13 varchar(16),#in14 varchar(12),#in15 varchar(14),#in16 varchar(16),
#in17 varchar(11),#in18 varchar(15),#in19 varchar(6),#in20 varchar(12),
#in21 varchar(12),#in22 varchar(10),#in23 varchar(15),#in24 varchar(15),
#in25 varchar(15),#in26 varchar(11),#in27 varchar(16),#in28 varchar(20),
#in29 varchar(6),#in30 varchar(16),#in31 varchar(17),#in32 varchar(11),
#in33 varchar(18),#in34 varchar(23),#in35 varchar(14),#in36 varchar(19),
#in37 varchar(12),#in38 varchar(14)',
#quote_status_id0 = '1', ### = NULL, #in1 = 'Widget1', #in2 = 'Widget2',
#in3 = 'Widget3', #in4 = 'Widget4', #in5 = 'Widget5', #in6 = 'Widget6', #in7 = 'Widget7',
#in8 = 'Widget7', #in9 = 'Widget7', #in10 = 'Widget8', #in11 = 'Widget9', #in12 = 'Widget10',
#in13 = 'Widget11', #in14 = 'Widget12', #in15 = 'Widget13', #in16 = 'Widget14',
#in17 = 'Widget15', #in18 = 'Widget16', #in19 = 'Widget17', #in20 = 'Widget18',
#in21 = 'DWidget19', #in22 = 'Widget20', #in23 = 'Widget21', #in24 = 'Widget22',
#in25 = 'Widget23', #in26 = 'Widget24', #in27 = 'Widget25', #in28 = 'Widget26',
#in29 = 'Widget27', #in30 = 'Widget28', #in31 = 'Widget29', #in32 = 'Widget30',
#in33 = 'Widget31', #in34 = 'Widget32', #in35 = 'Widget33', #in36 = 'Widget34',
#in37 = 'Widget35', #in38 = 'Widget36'
If you have to ask this question, you should probably use a temp table. Insert your parameters to the temp table and either JOIN your main table to it, or use an IN() predicate against a subquery of the temp table.
In most cases when you have 30+ parameters in an IN() predicate, you're going to find that you need more periodically. Using a temp table allows you to keep increasing the number of values without having to rewrite your query.
And it avoids any possibility of hitting a limit of the number of parameters or a limit on query length.

Resources