ECPG: sizeof() in EXEC SQL DECLARE SECTION - sql

I have Sybase ASE CPRE Embedded SQL С code:
void MyFunc( MyClass*unit_address )
{
EXEC SQL BEGIN DECLARE SECTION;
CS_BINARY var1[sizeof(MyClass)];
EXEC SQL END DECLARE SECTION;
}
Try to migrate to PostgreSQL ECPG Embedded SQL С code:
void MyFunc( MyClass*unit_address )
{
EXEC SQL BEGIN DECLARE SECTION;
unsigned char var1[sizeof(MyClass)];
EXEC SQL END DECLARE SECTION;
}
But ecpg.exec pre-compiler returns:
d:\>"c:\Program Files\PostgreSQL\9.3\bin\ecpg.exe"-o 1.c 1.pgc
1.pgc: 4: ERROR: syntax error at or near "("
error deleting output file "1.c"
My solution:
void MyFunc( MyClass*unit_address )
{
#define VAR1_SIZEOF sizeof(MyClass)
EXEC SQL BEGIN DECLARE SECTION;
unsigned char var1[VAR1_SIZEOF];
EXEC SQL END DECLARE SECTION;
#undef VAR1_SIZEOF
}
C code of function after pre-compile:
void MyFunc( MyClass*unit_address )
{
#define VAR1_SIZEOF sizeof(MyClass)
/* exec sql begin declare section */
#line 1 "1.pgc"
void MyFunc( MyClass*unit_address )
{
#define VAR1_SIZEOF sizeof(MyClass)
/* exec sql begin declare section */
#line 5 "1.pgc"
unsigned char var1 [ VAR1_SIZEOF ] ;
/* exec sql end declare section */
#line 6 "1.pgc"
#undef VAR1_SIZEOF
}
but perhaps there is a more correct decision.

Related

Converting double to string in Oracle pro*c

Is there any way to convert a double value to string without losing any digit in Oracle pro*c? The precision varies as the column from which value is fetched is NUMBER(10,8)
Like it was mentioned in comments you can use TO_CHAR to convert to a string. In Pro*C it would look something like this:
EXEC SQL DECLARE num_test_cursor CURSOR FOR SELECT TO_CHAR(num) FROM numtest;
Then you can fetch it into a variable:
EXEC SQL FETCH num_test_cursor INTO :number_string;
Finally with
number_string[strcspn(number_string, " ")] = '\0';
you can remove all padding space characters at the end.
Test
Create a table in an SQL client, e.g. SQLPlus, and fill it with some test entries:
CREATE TABLE numtest ( num NUMBER(10,8));
INSERT INTO numtest VALUES (99.99999999);
INSERT INTO numtest VALUES (3.141592654);
INSERT INTO numtest VALUES (0.00000001);
INSERT INTO numtest VALUES (1.23);
Complete, Self-contained Pro*C Program
exec sql begin declare section;
char *connectString = "scott/tiger#pdb";
int limit;
char number_string[11 + 1]; //number(10,8) + NUL
exec sql end declare section;
exec sql include sqlca;
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int main(void) {
exec sql connect :connectString;
if(sqlca.sqlcode == 0) {
printf("connected to db\n");
} else {
fprintf(stderr, "failed:%s (error code=%d)\n", sqlca.sqlerrm.sqlerrmc, sqlca.sqlcode);
exit(1);
}
EXEC SQL SELECT COUNT(*) INTO :limit FROM numtest;
printf("row count: %d\n", limit);
EXEC SQL DECLARE num_test_cursor CURSOR FOR SELECT TO_CHAR(num) FROM numtest;
EXEC SQL FOR :limit OPEN num_test_cursor;
int row;
for(row = 0; row < limit; row++) {
EXEC SQL FETCH num_test_cursor INTO :number_string;
number_string[strcspn(number_string, " ")] = '\0';
printf("number as string: \"%s\"\n", number_string);
}
_getch();
return 0;
}
The debug outputs of the program confirm the desired result:
connected to db
row count: 4
number as string: "99.99999999"
number as string: "3.14159265"
number as string: ".00000001"
number as string: "1.23"

Is there a difference between using DECLARE and passing values to a stored procedure

Is there any difference between these two different ways of calling stored procedures? How does it effect parameterization?
DECLARE #RC int
DECLARE #ixMachineType int = 1
DECLARE #ixMachineModel int = NULL
DECLARE #dblRpm float = NULL
DECLARE #iOffset int = 0
DECLARE #PageSize int = 10
EXECUTE #RC = [dbo].[uspGet_MachineModel]
#ixMachineType
,#ixMachineModel
,#dblRpm
,#iOffset
,#PageSize
GO
and
EXECUTE [dbo].[uspGet_MachineModel] 1, NULL, NULL, 0, 10

RPG exec sql works only once

I wrote program in RPG IV free-form and i met a problem. Im trying to execute sql statment with:
dcl-proc getRecord;
dcl-pi *N int(5) end-pi;
dcl-s rec int(5) inz(0);
exec sql
select max(SCORE) into :rec from SNK_HISC;
return rec;
END-PROC;
It works only once after compilation. Maybe i should reset some indicators or sql flags? At the end of program i use:
*inlr = *on;
return;
Where procedure is called:
exfmt BACK;
exfmt INFO;
inital();
dow run and alive;
write MAINBOARD;
READ(E) AKE_DSP;
run = FKeyListener();
alive = goForward();
ENDDO;
LSCORE = points;
if points > getRecord();
LRECORD = 'NEW RECORD!';
exec sql
insert into AKE_HISC( USID , SCORE) VALUES( :userID , :points);
ENDIF;
exfmt ENDING;
*inlr = *on;
return;
And in this procedure:
dcl-proc inital;
snake(1).x = 5;
snake(2).x = 5;
snake(3).x = 5;
snake(1).y = 5;
snake(2).y = 6;
snake(3).y = 7;
direction.x = 1;
direction.y = 0;
SCORE = points;
RECORD = getRecord();
genSnack();
refresh();
END-PROC;
I run program with this CL program:
PGM
MONMSG MSGID(CPF0000 MCH0000) EXEC(GOTO CMDLBL(END))
OVRDSPF FILE(AKE_DSP) DEV(*REQUESTER) WAITRCD(1)
CALL PGM(AKE_S)
END:
DLTOVR FILE(*ALL)
MONMSG MSGID(CPF0000)
ENDPGM
Problem was not with sql query but with that where it is. I removed procedure getRecord() and make rec global variable and the sql query was placed inside the main cycle thats all.

Program with embedded sql gives compilation error

#include<stdio.h>
#include<error.h>
#include<sys/shm.h>
#include "/opt/PostgreSQL/9.1/include/libpq-fe.h"
int main()
{
PGconn *conn;
int buf_ptr=0;
int i;
{
fprintf(stderr,"connection to database failed:%s",PQerrorMessage(conn));
exit(0);
}
else
{
printf("connection to database successful \n");
}
printf("Do you want to create a table enter 1 \n ");
scanf("%d",&i);
if(i==1)
{
EXEC SQl CREATE TABLE EMPOYE(
ENO INT,
ENAME VARCHAR(10));
}
return 0;
}
hello i am a newbie i am learning embedded c
i want to create a simple code where a table is created in c
when i am compiling the above program i am getting error like
embc.c:25: error: âEXECâ undeclared (first use in this function)
embc.c:25: error: (Each undeclared identifier is reported only once
embc.c:25: error: for each function it appears in.)
embc.c:25: error: expected â;â before âSQlâ
please help
First, the connection to database is missing, you should have something like :
int i=0;
EXEC SQL CONNECT TO target [AS connection-name] [USER user-name];
Or
PGconn *conn;
int buf_ptr=0;
int i=0;
conn = PQconnectdbParams(const char **keywords, const char **values, int expand_dbname);
then save your source file as prog.pgc and run :
ecpg prog.pgc
this will create a file called prog.c which can be compiled as a standard C file.

Oracle Pro*C updating table with cursor failed

I have a table like this:
CREATE TABLE book_info (
book_id VARCHAR(32) not null,
title varchar(255) not null,
author varchar(255) not null,
folder_path varchar(255) not null,
primary key(book_id)
);
And i insert this data on it:
insert into book_info values('BOOK1', 'APUE', 'Richard Stevens', '/home/user1/unix_programming_books');
insert into book_info values('BOOK2', 'Unix Network programming', 'Richard Stevens', '/home/user1/unix_programming_books');
insert into book_info values('BOOK3', 'Core Python Applications Programming', 'Wesley J. Chun', '/home/user1/python_programming_books');
I'm trying to update this table using Oracle PRO*C, but i can't! below is my code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
EXEC SQL INCLUDE SQLCA;
EXEC SQL INCLUDE ORACA;
#define USER_LEN 10
#define PASS_LEN 10
VARCHAR user[USER_LEN];
VARCHAR pass[PASS_LEN];
#define STRCPY_TO_ORA(dest, source)\
dest.len = strlen(source);\
strcpy((char *)dest.arr, (const char *)source)
#define STRCPY_FROM_ORA(dest, source)\
source.arr[source.len] = 0;\
strcpy((char *)dest,(const char *)source.arr)
/* Connecting to the database */
int db_connection(char *db_user, char *db_pass)
{
strncpy((char *) user.arr, db_user, USER_LEN);
user.len = strlen((char *) user.arr);
strncpy((char *) pass.arr, db_pass, PASS_LEN);
pass.len = strlen((char *) pass.arr);
EXEC SQL CONNECT :user IDENTIFIED BY :pass;
if (sqlca.sqlcode != 0)
{
fprintf(stdout, "Connection failed:%s\n", sqlca.sqlerrm.sqlerrmc);
return(sqlca.sqlcode);
}
fprintf(stdout, "Connected to ORACLE as user:%s\n", user.arr);
return (sqlca.sqlcode);
}
int book_not_found_function(char *path)
{
fprintf(stdout, "%s\n", __FUNCTION__);
}
int path_update_success_function(char *book_id, char *new_path)
{
fprintf(stdout, "Update book %s path to %s\n", book_id, new_path);
}
void other_function(void)
{
fprintf(stdout, "%s\n", __FUNCTION__);
}
/* Updating books path */
int books_path_updating(char *old_path, char *new_path)
{
char book_id_string[32];
EXEC SQL BEGIN DECLARE SECTION;
varchar sql_old_path[255];
varchar sql_new_path[255];
varchar sql_book_id[32];
EXEC SQL END DECLARE SECTION;
STRCPY_TO_ORA(sql_old_path, old_path);
STRCPY_TO_ORA(sql_new_path, new_path);
/* Declare a cursor for the FETCH statement. */
EXEC SQL DECLARE books_cursor CURSOR FOR
SELECT BOOK_ID
FROM BOOK_INFO
WHERE FOLDER_PATH = :sql_old_path;
if (sqlca.sqlcode != 0)
{
fprintf(stdout, "Declare cursor failed\n");
fprintf(stdout, "Oracle error %s\n", sqlca.sqlerrm.sqlerrmc);
return(sqlca.sqlcode);
}
EXEC SQL OPEN books_cursor;
if (sqlca.sqlcode != 0)
{
fprintf(stdout, "Open cursor failed\n");
fprintf(stdout, "Oracle error %s\n", sqlca.sqlerrm.sqlerrmc);
return(sqlca.sqlcode);
}
for ( ;; )
{
//EXEC SQL WHENEVER NOT FOUND DO break; // I used it but still nothing
//EXEC SQL WHENEVER NOT FOUND GOTO not_found; // I used this too
//EXEC SQL WHENEVER NOT FOUND DO continue; // I used this too
/* Fetching data */
EXEC SQL FETCH books_cursor
INTO :sql_book_id;
if (sqlca.sqlcode == 1403)
{
fprintf(stdout, "No book found for this folder %s\n", old_path);
book_not_found_function(old_path);
return 0;
}
else if (sqlca.sqlcode != 0)
{
fprintf(stdout, "Oracle error %s\n", sqlca.sqlerrm.sqlerrmc);
EXEC SQL CLOSE books_cursor;
return (sqlca.sqlcode);
}
else
{
STRCPY_FROM_ORA(book_id_string, sql_book_id);
fprintf(stdout, "BOOK_ID = %s\n", book_id_string);
/* Updating the path */
EXEC SQL UPDATE BOOK_INFO
SET FOLDER_PATH =:sql_new_path
WHERE BOOK_ID =:sql_book_id;
if (sqlca.sqlcode != 0)
{
fprintf(stdout, "Oracle error %s\n", sqlca.sqlerrm.sqlerrmc);
EXEC SQL CLOSE books_cursor;
return (sqlca.sqlcode);
}
else
{
path_update_success_function(book_id_string, new_path);
}
}
}
EXEC SQL CLOSE books_cursor;
other_function();
EXEC SQL COMMIT WORK RELEASE;
return 0;
}
int main(int argc, char **argv)
{
db_connection("evariste", "123456");
books_path_updating("/home/user1/unix_programming_books", "/home/user1/UNIX_PROGRAMMING_BOOKS");
books_path_updating("/non_existing_path", "/non_existing_path");
return 0;
}
This program produce the output :
Connected to ORACLE as user:evariste
BOOK_ID = BOOK1
Update book BOOK1 path to /home/user1/UNIX_PROGRAMMING_BOOKS
BOOK_ID = BOOK2
Update book BOOK2 path to /home/user1/UNIX_PROGRAMMING_BOOKS
No book found for this folder /home/user1/unix_programming_books // WHEY THIS?
book_not_found_function // WHY THIS
Declare cursor failed // WHY THIS
Oracle error ORA-01403: no data found // WHY THIS
The table is not updated and the functions path_update_success_function and other_function are never executed! Why this?
Thanks for your help.
Connected to ORACLE as user:evariste
BOOK_ID = BOOK1
Update book BOOK1 path to /home/user1/UNIX_PROGRAMMING_BOOKS
BOOK_ID = BOOK2
Update book BOOK2 path to /home/user1/UNIX_PROGRAMMING_BOOKS
No book found for this folder /home/user1/unix_programming_books // WHEY THIS?
You've fetched past the end of the resultset. Two rows match the cursor this time, so the first two fetches succeed; the third gets no data. This is expected and you shouldn't treat this as an error - just break the loop, which will also cause other_function to be called.
book_not_found_function // WHY THIS
Because you treat 1403 as an error. If you want to call this function when there are no matches, you'll need to count in the loop, and call it afterwards if needed.
Declare cursor failed   // WHY THIS
Oracle error ORA-01403: no data found // WHY THIS
sqlca.sqlcode seems to still be set from the earlier fetch, so this is misleading.
As far as I can remember you'd normally declare the cursor once in the file, not each time the function is called; not sure if Pro*C just ignores the redefinition. You can look at the generated file to see how it deals with it. You also won't get a runtime error from this, if it's wrong it won't (pre-)compile.
The table is not updated and the functions
path_update_success_function and other_function are never executed!
Why this?
path_update_success is called for the first two fetches, but not for the third which fails, and not for the second path because the function returns due to the apparent declare cursor before it gets near it. other_function isn't called because for both calls you return from the function before you can reach it. Similarly the table seems to not be updated because you return before you commit. Unlike SQL*Plus, Pro*C doesn't automatically commit on exit, so there is an implicit rollback. Note also that if you did get to the commit, the release disconnects you, so the second time you'd get a not-connected-to-Oracle error. You should decide to commit/rollback once really, probably right at the end of main.
Untested modification:
int books_path_updating(char *old_path, char *new_path)
{
char book_id_string[32];
int books_found;
EXEC SQL BEGIN DECLARE SECTION;
varchar sql_old_path[255];
varchar sql_new_path[255];
varchar sql_book_id[32];
EXEC SQL END DECLARE SECTION;
STRCPY_TO_ORA(sql_old_path, old_path);
STRCPY_TO_ORA(sql_new_path, new_path);
/* Declare a cursor for the FETCH statement */
EXEC SQL DECLARE books_cursor CURSOR FOR
SELECT BOOK_ID
FROM BOOK_INFO
WHERE FOLDER_PATH = :sql_old_path;
EXEC SQL OPEN books_cursor;
if (sqlca.sqlcode != 0)
{
fprintf(stdout, "Open cursor failed\n");
}
books_found = 0;
while (sqlca.sqlcode == 0)
{
/* Fetching data */
EXEC SQL FETCH books_cursor
INTO :sql_book_id;
if (sqlca.sqlcode != 0)
{
break;
}
STRCPY_FROM_ORA(book_id_string, sql_book_id);
fprintf(stdout, "BOOK_ID = %s\n", book_id_string);
/* Updating the path */
EXEC SQL UPDATE BOOK_INFO
SET FOLDER_PATH = :sql_new_path
WHERE BOOK_ID = :sql_book_id;
if (sqlca.sqlcode != 0)
{
break;
}
/* Track how many books we found, though we only really care later that
* this is non-zero */
books_found++;
path_update_success_function(book_id_string, new_path);
}
EXEC SQL CLOSE books_cursor;
/* Check for and display error, but ignore 1403 as this just indicates the
* end of the result set */
if ((sqlca.sqlcode != 0) && (sqlca.sqlcode != 1403))
{
fprintf(stdout, "Oracle error %s\n", sqlca.sqlerrm.sqlerrmc);
return 1;
}
if (books_found == 0)
{
fprintf(stdout, "No book found for this folder %s\n", old_path);
book_not_found_function(old_path);
return 0;
}
other_function();
return 0;
}
int main(int argc, char **argv)
{
int rc;
rc = db_connection("evariste", "123456");
/* Only do the first path if we didn't get an error connecting */
if (rc == 0)
{
rc == books_path_updating("/home/user1/unix_programming_books",
"/home/user1/UNIX_PROGRAMMING_BOOKS");
}
/* Only do the next path if we didn't get an error from the previous one */
if (rc == 0)
{
rc = books_path_updating("/non_existing_path",
"/non_existing_path");
}
/* Decide whether to rollback or commit; this assumes you don't want to
* keep any changes if there are any errors */
if (rc != 0)
{
EXEC SQL ROLLBACK WORK RELEASE;
return 1;
}
EXEC SQL COMMIT WORK RELEASE;
return 0;
}
Seems DECLARE CURSOR does not set sqlca.sqlcode.
The error you've got was the previous one when you achieved the end of your fetch.
So you should not test errors after a DECLARE CURSOR, but after the OPEN CURSOR only.