Exemplo n.º 1
0
    // TODO Rewrite login so that it does not use an object for a parameter. +callback?
    // assumes {userId: 'user name', password: '******', server: 'server', database: 'database' }
    // returns a database reference
    static v8::Handle<Value> Login(const Arguments& args) {
      v8::HandleScope scope;
      LOGINREC *login;
      DBPROCESS *dbconn;

      REQ_OBJ_ARG(0, connArgs);

      /* Allocate a login params structure */
      if ((login = dblogin()) == FAIL) {
        return v8::ThrowException(v8::Exception::Error(v8::String::New("FreeTDS cannot initialize dblogin() structure.")));
      }

      // fill out the login params
      v8::Local<v8::String> userIdKey = v8::String::New("userId");
      if(connArgs->Has(userIdKey)){
        String::AsciiValue userId(connArgs->Get(userIdKey));
        DBSETLUSER(login, *userId);
      }

      v8::Local<v8::String> passwordKey = v8::String::New("password");
      if(connArgs->Has(passwordKey)){
        String::AsciiValue password(connArgs->Get(passwordKey));
        DBSETLPWD(login, *password);
      }

      // set the application name to node-freetds to help with profiling etc
      DBSETLAPP(login, "node-freetds");      

      v8::Local<v8::String> serverKey = v8::String::New("server");
      if(!connArgs->Has(serverKey)){
        dbloginfree(login);
        return v8::ThrowException(v8::Exception::Error(v8::String::New("The server name was not provided")));
      }
      String::AsciiValue serverName(connArgs->Get(serverKey));
      
      /* Now connect to the DB Server */
      if ((dbconn = dbopen(login, *serverName)) == NULL) {
        dbloginfree(login);
        return v8::ThrowException(v8::Exception::Error(v8::String::New("FreeTDS cannot initialize dblogin() structure.")));
      }

      v8::Local<v8::String> dbKey = v8::String::New("database");
      if(connArgs->Has(dbKey)){
        String::AsciiValue database(connArgs->Get(dbKey));
        /* Now switch to the correct database */
        if ((dbuse(dbconn, *database)) == FAIL) {
          dbloginfree(login);
          return v8::ThrowException(v8::Exception::Error(v8::String::New("FreeTDS could not switch to the database")));
        }
      }

      // free the login struct because we don't need it anymore
      dbloginfree(login);

      // wrap the dbconn so that we can persist it from the JS side
      return v8::External::Wrap(dbconn);
    }
Exemplo n.º 2
0
int
main(int argc, char **argv)
{
	LOGINREC *login;

	read_login_info(argc, argv);

	fprintf(stdout, "Starting %s\n", argv[0]);

	dbinit();

	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	fprintf(stdout, "About to logon\n");

	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "thread");

	fprintf(stdout, "About to open \"%s\"\n", SERVER);

	dbproc = dbopen(login, SERVER);
	if (!dbproc) {
		fprintf(stderr, "Unable to connect to %s\n", SERVER);
		return 1;
	}

	dbloginfree(login);

	if (strlen(DATABASE))
		dbuse(dbproc, DATABASE);

	test("VARCHAR(10)", 1);
	test("CHAR(10)", 1);
	test("TEXT", 1);

	test("NVARCHAR(10)", 0);
#ifndef DBNTWIN32
	if (dbtds(dbproc) >= DBTDS_7_0)
		test("NTEXT", 0);
#endif

	test("VARCHAR(MAX)", 0);
#ifndef DBNTWIN32
	if (dbtds(dbproc) >= DBTDS_7_0)
		test("NVARCHAR(MAX)", 0);
#endif

	dbexit();

	return failed ? 1 : 0;
}
Exemplo n.º 3
0
int
main(int argc, char *argv[])
{
	LOGINREC *login;
	DBPROCESS *dbproc;
	int ret_code;
	int num_cols;
	int num_res;

	set_malloc_options();

	read_login_info(argc, argv);
	printf("Starting %s\n", argv[0]);
	dbinit();

	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	printf("About to logon\n");

	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "t0012");

	dbproc = dbopen(login, SERVER);
	if (strlen(DATABASE)) {
		dbuse(dbproc, DATABASE);
	}
	dbloginfree(login);
	printf("After logon\n");

	/* select */
	sql_cmd(dbproc);
	dbsqlexec(dbproc);

	num_res = 0;
	while ((ret_code = dbresults(dbproc)) == SUCCEED) {
		num_cols = dbnumcols(dbproc);
		printf("Result %d has %d columns\n", num_res, num_cols);
		if (!(num_res % 2) && num_cols)
			set_failed();
		while(dbnextrow(dbproc) != NO_MORE_ROWS) {};
		num_res++;
	}
	if (ret_code == FAIL)
		set_failed();

	dbclose(dbproc);
	dbexit();

	printf("%s %s\n", __FILE__, (failed ? "failed!" : "OK"));
	return failed ? 1 : 0;
}
Exemplo n.º 4
0
int
main(int argc, char **argv)
{
	LOGINREC *login;
	DBPROCESS *dbproc;

	read_login_info(argc, argv);
	printf("Starting %s\n", argv[0]);

	dbinit();

	printf("About to logon\n");

	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "t0011");

	printf("About to open\n");

	dbproc = dbopen(login, SERVER);
	if (strlen(DATABASE))
		dbuse(dbproc, DATABASE);
	dbloginfree(login);

	printf("Dropping table\n");
	sql_cmd(dbproc);
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}

	printf("creating table\n");
	sql_cmd(dbproc);
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}

	printf("insert\n");

	insert_row(dbproc);
	insert_row(dbproc);
	insert_row(dbproc);

	failed = select_rows(dbproc, STRINGBIND);

	dbexit();

	printf("%s %s\n", __FILE__, (failed ? "failed!" : "OK"));
	return failed ? 1 : 0;
}
Exemplo n.º 5
0
int main(void)
{

  /* initialize db library */
  if (dbinit() == FAIL)
    return 0;

  /* set message and error handler routines */
  dberrhandle((EHANDLEFUNC)err_handler);
  dbmsghandle((MHANDLEFUNC)msg_handler);

  /* create login, user and pw are stored in  sybdbex.h */
  login = dblogin();
  DBSETLUSER(login, USER);
  DBSETLPWD(login, PASSWORD);
  DBSETLAPP(login, "store_beispiel");

  /* login to server */
  dbproc = dbopen(login, "syb150");
  dbuse(dbproc, "ma11s61406"); 

  while(1)
  {
    get_berufe();

    printf("beruf?\n");
    gets(answer);
    
    if(strcmp(answer, "")==0)
      continue;
  while(1)
  {
    get_mitarbeiter(answer);

    printf("mitnr?\n");
    gets(answer);

    if(strcmp(answer, "")==0)
      break;
    get_all(answer);
    break;
  }
  }

    /* dbexit(STDEXIT); */
    dbexit();
    exit(STDEXIT);
}
Exemplo n.º 6
0
static void *
thread_test(void * arg)
{
	int i;
	int num = ptr2int(arg);
	DBPROCESS *dbproc;
	LOGINREC *login;

	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "thread");

	dbproc = dbopen(login, SERVER);
	if (!dbproc) {
		dbloginfree(login);
		fprintf(stderr, "Unable to connect to %s\n", SERVER);
		set_failed();
		return NULL;
	}
	dbloginfree(login);

	if (strlen(DATABASE))
		dbuse(dbproc, DATABASE);

	pthread_mutex_lock(&mutex);
	++thread_count;
	pthread_mutex_unlock(&mutex);

	printf("thread %2d waiting for all threads to start\n", num+1);
	pthread_mutex_lock(&mutex);
	while (thread_count < NUM_THREAD) {
		pthread_mutex_unlock(&mutex);
		sleep(1);
		pthread_mutex_lock(&mutex);
	}
	pthread_mutex_unlock(&mutex);

	for (i = 1; i <= NUM_LOOP; ++i) {
		printf("thread %2d of %2d loop %d\n", num+1, NUM_THREAD, i);
		if (test(dbproc) || result != 0)
			break;
	}

	dbclose(dbproc);
	return NULL;
}
Exemplo n.º 7
0
void Connector::set_login_struct(string user , string password )
{
	if ( (login_rec = dblogin()) == FAIL){
		conn_status = false;
		s_error_message.append("Failed to initialize the login struct");
		error_code = 2;
	}

	DBSETLUSER(login_rec, user.c_str());
	DBSETLPWD(login_rec, password.c_str());
	DBSETLAPP(login_rec, "msfmobile");

	char hostname[MAXHOSTNAMELEN];
	int max_len = MAXHOSTNAMELEN;

	if (gethostname(hostname, max_len) == 0){
		DBSETLHOST(login_rec, hostname);
	}
}
Exemplo n.º 8
0
int init_db(void){
	/* initialize db library */
	if (dbinit() == FAIL)
		return 0;

	/* set message and error handler routines */
	dberrhandle((EHANDLEFUNC)err_handler);
	dbmsghandle((MHANDLEFUNC)msg_handler);

	/* create login, user and pw are stored in  sybdbex.h */
	login = dblogin();
	DBSETLUSER(login, USER);
	DBSETLPWD(login, PASSWORD);
	DBSETLAPP(login, "berufe");

	/* login to server */
	dbproc = dbopen(login, "syb150");
	dbproc_insert = dbopen(login, "syb150");
	dbuse(dbproc, "ma11s67778");
	dbuse(dbproc_insert, "ma11s67778");

}
Exemplo n.º 9
0
int syb_connect (char *name, char *passwd, char *appl, char *host)
{

  clear_error ();
  
  DBSETLUSER (login, name);
  
  DBSETLPWD (login, passwd);
  
  if (strlen (appl) > 0)
    {
      DBSETLAPP (login, appl);
    }
  
  if (strlen (host) > 0)
    {
      DBSETLHOST (login, host);
    }
  
  descriptor[PRIVATE_DESCRIPTOR] = dbopen (login, NULL); /*for internal use*/
  
  return error_number;
}
Exemplo n.º 10
0
DBPROCESS	*ConnectDB()
{
	DBPROCESS   *dbproc;
	LOGINREC    *login;

	putenv("TDSVER=42");
	dbinit();
	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);
	login = dblogin();
	DBSETLPWD(login, "yjkim");
	DBSETLUSER(login, "tim_yjkim");
	DBSETLAPP(login, "Sync");
	DBSETLHOST(login, "auth01");

	dbproc = dbopen(login, "webDB");
	if(!dbproc) {
		fprintf(stderr, "Unable to Connect to %s", "webDB");
		exit(-1);
	}

	dbloginfree(login);
	return	dbproc;
}
Exemplo n.º 11
0
int
main(int argc, char *argv[])
{
	int echo = 0;

#ifdef notyet
	int print_statistics = 0;
#endif
	int fipsflagger = 0;
	int perfstats = 0;
	int no_prompt = 0;
	int use_encryption = 0;
	int chained_transactions = 0;
	const char *cmdend = "go";
	int headers = 0;
	char *columnwidth = NULL;
	const char *colseparator = " ";
	const char *lineseparator = "\n";
	int timeout = 0;
	char *username = NULL;
	char *password = NULL;
	char *server = NULL;
	DBCHAR *char_set = NULL;
	const char *editor;
	char *hostname = NULL;
	char *sqlch;
	char *interfaces_filename = NULL;
	char *input_filename = NULL;
	char *output_filename = NULL;
	int logintime = -1;
	char *language = NULL;
	int size = 0;
	char *sybenv;
	DBPROCESS *dbproc;
	LOGINREC *login;
	char **ibuf = NULL;
	int ibuflines = 0;
	int printedlines;
	int i;
	char *line;
	int dbrc;
	char foobuf[512];
	char *firstword;
	char *cp;
	int c;
	int errflg = 0;
	char *prbuf;
	int prbuflen;
	FILE *fp;
	FILE *tmpfp;
	FILE *tmpfp2;
	char *tfn;
	char tmpfn[256];
	int num_cols;
	int selcol;
	int col;
	int collen;
	DBINT colid;
	const char *opname;
	char adbuf[512];
	DBINT convlen;
	int printedcompute = 0;
	char adash;
	const char *database_name = NULL;
	int default_exit = EXIT_SUCCESS;

	setlocale(LC_ALL, "");

#ifdef __VMS
	/* Convert VMS-style arguments to Unix-style */
	parse_vms_args(&argc, &argv);
#endif

	editor = getenv("EDITOR");
	if (!editor) {
		editor = getenv("VISUAL");
	}
	if (!editor) {
		editor = "vi";
	}

	opterr = 0;
	optarg = NULL;
	while (!errflg && (c = getopt(argc, argv, "eFgpnvXYa:c:D:E:h:H:i:I:J:l:m:o:P:s:S:t:U:w:y:z:A:"))
	       != -1) {
		switch (c) {
		case 'e':
			echo = 1;
			break;
		case 'F':
			fipsflagger = 1;
			break;
		case 'g':
			errflg++;
			break;
		case 'p':
			errflg++;
			perfstats = 1;
			break;
		case 'n':
			no_prompt = 1;
			break;
		case 'v':
			puts("fisql, a free isql replacement by Nicholas S. Castellano");
			exit(EXIT_SUCCESS);
			break;
		case 'X':
			/* XXX: We get a different error message than isql gives; neither seems
			 * to work
			 */
			use_encryption = 1;
			break;
		case 'Y':
			chained_transactions = 1;
			break;
		case 'c':
			cmdend = optarg;
			break;
		case 'E':
			editor = optarg;
			break;
		case 'h':
			headers = atoi(optarg);
			break;
		case 'H':
			hostname = optarg;
			break;
		case 'i':
			input_filename = optarg;
			break;
		case 'I':
			interfaces_filename = optarg;
			break;
		case 'J':
			errflg++;
			break;
		case 'l':
			logintime = atoi(optarg);
			break;
		case 'm':
			global_errorlevel = atoi(optarg);
			break;
		case 'o':
			output_filename = optarg;
			break;
		case 'P':
			password = optarg;
			break;
		case 's':
			colseparator = optarg;
			break;
		case 'S':
			server = optarg;
			break;
		case 't':
			timeout = atoi(optarg);
			break;
		case 'U':
			username = optarg;
			break;
		case 'w':
			columnwidth = optarg;
			break;
		case 'y':
			/* XXX: this doesn't seem to be what isql does with -y...it doesn't
			 * seem to do anything actually
			 */
			sybenv = (char *) xmalloc((strlen(optarg) + 8) * sizeof(char));
			strcpy(sybenv, "SYBASE=");
			strcat(sybenv, optarg);
			putenv(sybenv);
			break;
		case 'z':
			language = optarg;
			break;
		case 'A':
			size = atoi(optarg);
			break;
		case 'D':
			database_name = optarg;
			break;
		default:
			errflg++;
			break;
		}
	}

	if (errflg) {
		fprintf(stderr, "usage: fisql [-e] [-F] [-g] [-p] [-n] [-v] [-X] [-Y]\n");
		fprintf(stderr, "\t[-c cmdend] [-D database_name] [-E editor]\n");
		fprintf(stderr, "\t[-h headers] [-H hostname] [-i inputfile]\n");
		fprintf(stderr, "\t[-I interfaces_file] [-J client character set]\n");
		fprintf(stderr, "\t[-l login_timeout] [-m errorlevel]\n");
		fprintf(stderr, "\t[-o outputfile]\n");
		fprintf(stderr, "\t[-P password] [-s colseparator] [-S server]\n");
		fprintf(stderr, "\t[-t timeout] [-U username] [-w columnwidth]\n");
		fprintf(stderr, "\t[-y sybase_dir] [-z language]\n");
		exit(EXIT_FAILURE);
	}
	if (!(isatty(fileno(stdin)))) {
		no_prompt = 1;
		rl_outstream = fopen("/dev/null", "rw");
	}
	rl_readline_name = "fisql";
	rl_bind_key('\t', rl_insert);
	if (password == NULL) {
		password = (char *) xmalloc(READPASSPHRASE_MAXLEN);
		readpassphrase("Password: "******"r", stdin) == NULL) {
			/* XXX: sybase isql generates this error while parsing the options,
			 * but doesn't redirect the input until after the Password: prompt
			 */
			/* lack of newline for bug-compatibility with isql */
			fprintf(stderr, "Unable to open input file '%s'.", optarg);
			exit(EXIT_FAILURE);
		}
	}
	if (output_filename) {
		if (freopen(output_filename, "w", stdout) == NULL) {
			/* XXX: sybase isql generates this error while parsing the options,
			 * but doesn't redirect the output until after the Password: prompt
			 */
			/* lack of newline for bug-compatibility with isql */
			fprintf(stderr, "Unable to open output file '%s'.", output_filename);
			exit(EXIT_FAILURE);
		}
	}
	if (isatty(fileno(stdin))) {
		rl_outstream = stdout;
	}
	dbinit();
#if 0
#ifdef DBVERSION_100
	dbsetversion(DBVERSION_100);
#endif
#endif
	if ((login = dblogin()) == NULL) {
		reset_term();
		exit(EXIT_FAILURE);
	}
	dbmsghandle(msg_handler);
	dberrhandle(err_handler);
	DBSETLAPP(login, "fisql");
	if (username) {
		DBSETLUSER(login, username);
	}
	DBSETLPWD(login, password);
	memset(password, 0, strlen(password));

	if (char_set) {
		DBSETLCHARSET(login, char_set);
	}
	if (use_encryption) {
		DBSETLENCRYPT(login, TRUE);
	}
	if (hostname) {
		DBSETLHOST(login, hostname);
	}
	if (language) {
		DBSETLNATLANG(login, language);
	}
	if (size) {
		DBSETLPACKET(login, (short) size);
	}
	if (interfaces_filename) {
		dbsetifile(interfaces_filename);
	}
	dbsettime(timeout);
	if (logintime >= 0) {
		dbsetlogintime(logintime);
	}
	if ((dbproc = dbopen(login, server)) == NULL) {
		fprintf(stderr, "fisql: dbopen() failed.\n");
		reset_term();
		exit(EXIT_FAILURE);
	}

	dbsetopt(dbproc, DBPRLINESEP, lineseparator, strlen(lineseparator));
	if (colseparator) {
		dbsetopt(dbproc, DBPRCOLSEP, colseparator, strlen(colseparator));
	}
	if (columnwidth) {
		dbsetopt(dbproc, DBPRLINELEN, columnwidth, 0);
	}
	if (chained_transactions) {
		dbsetopt(dbproc, DBCHAINXACTS, NULL, 0);
	}
	if (fipsflagger) {
		dbsetopt(dbproc, DBFIPSFLAG, NULL, 0);
	}
	if (perfstats) {
		dbsetopt(dbproc, DBSTAT, "time", 0);
	}
	if (database_name) {
		dbuse(dbproc, database_name);
	}

	while (1) {
		if (sigsetjmp(restart, 1)) {
			if (ibuf) {
				for (i = 0; i < ibuflines; i++) {
					free(ibuf[i]);
				}
				ibuflines = 0;
				free(ibuf);
				ibuf = NULL;
			}
			fputc('\n', stdout);
			rl_on_new_line();
			rl_reset_line_state();
		}
		dbcancel(dbproc);
		signal(SIGINT, inactive_interrupt_handler);
		ibuf = (char **) xmalloc(sizeof(char *));
		ibuflines = 0;
		while (1) {
			if (no_prompt) {
				foobuf[0] = '\0';
			} else {
				sprintf(foobuf, "%d>> ", ibuflines + 1);
			}
			line = readline(foobuf);
			if (line == NULL) {
				line = "exit";
			}
			for (cp = line; *cp && isspace((unsigned char) *cp); cp++)
				continue;
			if (*cp) {
				add_history(line);
			}
			if (!(strncasecmp(line, "!!", 2))) {
				int rv;
				cp = line + 2;
				switch (rv = system(cp)) {
				case 0:
					continue;
				case -1:
					fprintf(stderr,
					    "Failed to execute `%s'\n", cp);
					continue;
				default:
					fprintf(stderr, "Command `%s' exited "
					    "with code %d\n", cp, rv);
					continue;
				}
			}
			/* XXX: isql off-by-one line count error for :r not duplicated */
			if (!(strncasecmp(line, ":r", 2))) {
				for (cp = line + 2; *cp && (isspace((unsigned char) *cp)); cp++)
					continue;
				tfn = cp;
				for (; *cp && !(isspace((unsigned char) *cp)); cp++)
					continue;
				*cp = '\0';
				if ((fp = fopen(tfn, "r")) == NULL) {
					fprintf(stderr, "Operating system error: Failed to open %s.\n", tfn);
					continue;
				}
				tmpfp = rl_instream;
				tmpfp2 = rl_outstream;
				rl_instream = fp;
				rl_outstream = fopen("/dev/null", "w");
				while ((line = readline("")) != NULL) {
					ibuf[ibuflines++] = line;
					ibuf = (char **) xrealloc(ibuf, (ibuflines + 1) * sizeof(char *));
				}
				rl_instream = tmpfp;
				fclose(rl_outstream);
				rl_outstream = tmpfp2;
				fclose(fp);
				fputc('\r', stdout);
				fflush(stdout);
				continue;
			}
			firstword = (char *) xmalloc((strlen(line) + 1) * sizeof(char));
			strcpy(firstword, line);
			for (cp = firstword; *cp; cp++) {
				if (isspace((unsigned char) *cp)) {
					*cp = '\0';
					break;
				}
			}
			if ((!(strcasecmp(firstword, "exit")))
			    || (!(strcasecmp(firstword, "quit")))) {
				reset_term();
				dbexit();
				exit(default_exit);
			}
			if (!(strcasecmp(firstword, "reset"))) {
				for (i = 0; i < ibuflines; i++) {
					free(ibuf[i]);
				}
				ibuflines = 0;
				continue;
			}
			if (!(strcasecmp(firstword, cmdend))) {
				if (ibuflines == 0) {
					continue;
				}
				free(firstword);
				break;
			}
			if ((!(strcasecmp(firstword, "vi")))
			    || (!(strcasecmp(firstword, editor)))) {
				int tmpfd;

				strcpy(tmpfn, "/tmp/fisqlXXXXXX");
				tmpfd = mkstemp(tmpfn);
				if ((fp = fdopen(tmpfd, "w")) == NULL) {
					perror("fisql");
					reset_term();
					dbexit();
					exit(2);
				}
				if (ibuflines) {
					for (i = 0; i < ibuflines; i++) {
						fputs(ibuf[i], fp);
						fputc('\n', fp);
						free(ibuf[i]);
					}
				} else {
					for (i = 0; ((sqlch = dbgetchar(dbproc, i)) != NULL); i++) {
						fputc(*sqlch, fp);
					}
				}
				fclose(fp);
				if (!(strcmp(firstword, "vi"))) {
					edit("vi", tmpfn);
				} else {
					edit(editor, tmpfn);
				}
				ibuflines = 0;
				fp = fopen(tmpfn, "r");
				tmpfp = rl_instream;
				rl_instream = fp;
				strcpy(foobuf, "1>> ");
				while ((line = readline(foobuf)) != NULL) {
					ibuf[ibuflines++] = line;
					sprintf(foobuf, "%d>> ", ibuflines + 1);
					ibuf = (char **) xrealloc(ibuf, (ibuflines + 1) * sizeof(char *));
				}
				rl_instream = tmpfp;
				fclose(fp);
				fputc('\r', stdout);
				fflush(stdout);
				unlink(tmpfn);
				continue;
			}
			free(firstword);
			ibuf[ibuflines++] = line;
			ibuf = (char **) xrealloc(ibuf, (ibuflines + 1) * sizeof(char *));
		}
		dbfreebuf(dbproc);
		for (i = 0; i < ibuflines; i++) {
			if (echo) {
				puts(ibuf[i]);
			}
			dbcmd(dbproc, ibuf[i]);
			dbcmd(dbproc, "\n");
			free(ibuf[i]);
		}
		free(ibuf);
		ibuf = NULL;
		signal(SIGINT, active_interrupt_handler);
		dbsetinterrupt(dbproc, (void *) active_interrupt_pending, (void *) active_interrupt_servhandler);
		if (dbsqlexec(dbproc) == SUCCEED) {
			maybe_handle_active_interrupt();
			while ((dbrc = dbresults(dbproc)) != NO_MORE_RESULTS) {
				printedlines = 0;
#define USE_DBPRROW 0
#if USE_DBPRROW
				dbprhead(dbproc);
				dbprrow(dbproc);
#else
				if ((dbrc == SUCCEED) && (DBROWS(dbproc) == SUCCEED)) {
					prbuflen = dbspr1rowlen(dbproc);
					prbuf = (char *) xmalloc(prbuflen * sizeof(char));
					dbsprhead(dbproc, prbuf, prbuflen);
					fputs(prbuf, stdout);
					fputc('\n', stdout);
					dbsprline(dbproc, prbuf, prbuflen, '-');
					fputs(prbuf, stdout);
					fputc('\n', stdout);
					maybe_handle_active_interrupt();
					while ((dbrc = dbnextrow(dbproc)) != NO_MORE_ROWS) {
						if (dbrc == FAIL) {
							break;
						}
						if (dbrc != REG_ROW) {
							num_cols = dbnumalts(dbproc, dbrc);
							for (selcol = col = 1; col <= num_cols; col++) {
								colid = dbaltcolid(dbproc, dbrc, col);
								while (selcol < colid) {
									collen = get_printable_column_size(dbproc, selcol);
									for (i = 0; i < collen; i++) {
										putchar(' ');
									}
									selcol++;
									printf("%s", colseparator);
								}
								opname = dbprtype(dbaltop(dbproc, dbrc, col));
								printf("%s", opname);
								collen = get_printable_column_size(dbproc, colid);
								collen -= strlen(opname);
								while (collen-- > 0) {
									putchar(' ');
								}
								selcol++;
								printf("%s", colseparator);
							}
							printf("%s", lineseparator);
							for (selcol = col = 1; col <= num_cols; col++) {
								colid = dbaltcolid(dbproc, dbrc, col);
								while (selcol < colid) {
									collen = get_printable_column_size(dbproc, selcol);
									for (i = 0; i < collen; i++) {
										putchar(' ');
									}
									selcol++;
									printf("%s", colseparator);
								}
								collen = get_printable_column_size(dbproc, colid);
								adash = '-';
								for (i = 0; i < collen; i++) {
									putchar(adash);
								}
								selcol++;
								printf("%s", colseparator);
							}
							printf("%s", lineseparator);
							for (selcol = col = 1; col <= num_cols; col++) {
								colid = dbaltcolid(dbproc, dbrc, col);
								while (selcol < colid) {
									collen = get_printable_column_size(dbproc, selcol);
									for (i = 0; i < collen; i++) {
										putchar(' ');
									}
									selcol++;
									printf("%s", colseparator);
								}
								convlen = dbconvert(dbproc,
										    dbalttype(dbproc, dbrc, col),
										    dbadata(dbproc, dbrc, col),
										    dbadlen(dbproc, dbrc, col),
										    SYBCHAR, (BYTE *) adbuf, sizeof(adbuf));
								printf("%.*s", (int) convlen, adbuf);
								collen = get_printable_column_size(dbproc, colid);
								collen -= convlen;
								while (collen-- > 0) {
									putchar(' ');
								}
								selcol++;
								printf("%s", colseparator);
							}
							printf("%s", lineseparator);
							printedcompute = 1;
							continue;
						}
						if (printedcompute || (headers && (printedlines >= headers)
								       && ((printedlines % headers) == 0))) {
							fputc('\n', stdout);
							dbsprhead(dbproc, prbuf, prbuflen);
							fputs(prbuf, stdout);
							fputc('\n', stdout);
							dbsprline(dbproc, prbuf, prbuflen, '-');
							fputs(prbuf, stdout);
							fputc('\n', stdout);
							printedcompute = 0;
						}
						printedlines++;
						dbspr1row(dbproc, prbuf, prbuflen);
						fputs(prbuf, stdout);
						fputc('\n', stdout);
						maybe_handle_active_interrupt();
					}
					fputc('\n', stdout);
					free(prbuf);
					maybe_handle_active_interrupt();
				}
#endif
				if (dbrc != FAIL) {
					if ((DBCOUNT(dbproc) >= 0) || dbhasretstat(dbproc)) {
						if (DBCOUNT(dbproc) >= 0) {
							fprintf(stdout, "(%d rows affected", (int) DBCOUNT(dbproc));
							if (dbhasretstat(dbproc)) {
								dbrc = dbretstatus(dbproc);
								fprintf(stdout, ", return status = %d", dbrc);
							}
							fprintf(stdout, ")\n");
						} else {
							if (dbhasretstat(dbproc)) {
								dbrc = dbretstatus(dbproc);
								fprintf(stdout, "(return status = %d)\n", dbrc);
							}
						}
					}
				}
			}
		} else {
			/* Something failed, so change the default
			 * exit status to reflect that.
			 */
			default_exit = EXIT_FAILURE;
		}
	}
	reset_term();
	dbexit();
	exit(EXIT_FAILURE);
	return (0);
}
Exemplo n.º 12
0
int
main(int argc, char **argv)
{
	int i;
	pthread_t th[NUM_THREAD];
	DBPROCESS *dbproc;
	LOGINREC *login;

	read_login_info(argc, argv);

	fprintf(stdout, "Start\n");

	dbinit();

	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	fprintf(stdout, "About to logon\n");

	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "thread");

	fprintf(stdout, "About to open \"%s\"\n", SERVER);

	dbproc = dbopen(login, SERVER);
	if (!dbproc) {
		fprintf(stderr, "Unable to connect to %s\n", SERVER);
		return 1;
	}

	dbloginfree(login);

	if (strlen(DATABASE))
		dbuse(dbproc, DATABASE);

	fprintf(stdout, "Dropping table\n");
	dbcmd(dbproc, "if object_id('dblib_thread') is not null drop table dblib_thread");
	dbsqlexec(dbproc);
	while (dbresults(dbproc) == SUCCEED) {
		/* nop */
	}

	fprintf(stdout, "creating table\n");
	dbcmd(dbproc, "create table dblib_thread (i int not null, s char(10) not null)");
	dbsqlexec(dbproc);
	while (dbresults(dbproc) == SUCCEED) {
		/* nop */
	}

	fprintf(stdout, "insert\n");
	for (i = 0; i < ROWS; i++) {
		char cmd[128];

		sprintf(cmd, "insert into dblib_thread values (%d, 'row %d')", i, i);
		dbcmd(dbproc, cmd);
		dbsqlexec(dbproc);
		while (dbresults(dbproc) == SUCCEED) {
			/* nop */
		}
	}

	for (i = 0; i < NUM_THREAD; ++i) {
		int err = pthread_create(&th[i], NULL, thread_test, int2ptr(i));
		if (err != 0)
		{
			fprintf(stderr, "Error %d (%s) creating thread\n", err, strerror(err));
			return 1;
		}
		/* MSSQL rejects the connections if they come in too fast */
		sleep(1);
	}

	for (i = 0; i < NUM_THREAD; ++i) {
		pthread_join(th[i], NULL);
		fprintf(stdout, "thread: %d exited\n", i + 1);
	}

	fprintf(stdout, "Dropping table\n");
	dbcmd(dbproc, "drop table dblib_thread");
	dbsqlexec(dbproc);
	while (dbresults(dbproc) == SUCCEED) {
		/* nop */
	}

	dbexit();

	return result;
}
Exemplo n.º 13
0
int
main(int argc, char **argv)
{
	char cmd[1024];
	LOGINREC *login;
	DBPROCESS *dbproc;
	int i;
	char teststr[1024];
	int erc, failed = 0;
	char *retname = NULL;
	int rettype = 0, retlen = 0;

	set_malloc_options();

	read_login_info(argc, argv);

	fprintf(stdout, "Start\n");
	add_bread_crumb();

	dbinit();

	add_bread_crumb();
	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	fprintf(stdout, "About to logon\n");

	add_bread_crumb();
	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "t0022");

	fprintf(stdout, "About to open\n");

	add_bread_crumb();
	dbproc = dbopen(login, SERVER);
	if (strlen(DATABASE))
		dbuse(dbproc, DATABASE);
	add_bread_crumb();
	dbloginfree(login);
	add_bread_crumb();

	fprintf(stdout, "Dropping proc\n");
	add_bread_crumb();
	dbcmd(dbproc, "if object_id('t0022') is not null drop proc t0022");
	add_bread_crumb();
	dbsqlexec(dbproc);
	add_bread_crumb();
	while ((erc = dbresults(dbproc)) == SUCCEED) {
		fprintf(stdout, "dbresult succeeded dropping procedure\n");
		while ((erc = dbnextrow(dbproc)) == SUCCEED) {
			fprintf(stdout, "dbnextrow returned spurious rows dropping procedure\n");
			assert(0); /* dropping a procedure returns no rows */
		}
		assert(erc == NO_MORE_ROWS);
	}
	assert(erc == NO_MORE_RESULTS);
	add_bread_crumb();

	fprintf(stdout, "creating proc\n");
	dbcmd(dbproc, "create proc t0022 (@b int out) as\nbegin\n select @b = 42\n return 66\nend\n");
	if (dbsqlexec(dbproc) == FAIL) {
		add_bread_crumb();
		fprintf(stdout, "Failed to create proc t0022.\n");
		exit(1);
	}
	while ((erc = dbresults(dbproc)) != NO_MORE_RESULTS) {
		assert(erc != FAIL);
		while ((erc = dbnextrow(dbproc)) == SUCCEED) {
			assert(0); /* creating a procedure returns no rows */
		}
		assert(erc == NO_MORE_ROWS);
	}

	sprintf(cmd, "declare @b int\nexec t0022 @b = @b output\n");
	fprintf(stdout, "%s\n", cmd);
	dbcmd(dbproc, cmd);
	dbsqlexec(dbproc);
	add_bread_crumb();


	while ((erc = dbresults(dbproc)) != NO_MORE_RESULTS) {
		if (erc == FAIL) {
			add_bread_crumb();
			fprintf(stdout, "Was expecting a result set.\n");
			exit(1);
		}
		while ((erc = dbnextrow(dbproc)) == SUCCEED) {
			assert(0); /* procedure returns no rows */
		}
		assert(erc == NO_MORE_ROWS);
	}

	add_bread_crumb();

#if defined(DBTDS_7_0) && defined(DBTDS_8_0) && defined(DBTDS_9_0)
	if ((dbnumrets(dbproc) == 0)
	    && ((DBTDS(dbproc) == DBTDS_7_0)
		|| (DBTDS(dbproc) == DBTDS_8_0)
		|| (DBTDS(dbproc) == DBTDS_9_0))) {
		fprintf(stdout, "WARNING:  Received no return parameters from server!\n");
		fprintf(stdout, "WARNING:  This is likely due to a bug in Microsoft\n");
		fprintf(stdout, "WARNING:  SQL Server 7.0 SP3 and later.\n");
		fprintf(stdout, "WARNING:  Please try again using TDS protocol 4.2.\n");
		dbcmd(dbproc, "drop proc t0022");
		dbsqlexec(dbproc);
		while (dbresults(dbproc) != NO_MORE_RESULTS) {
			/* nop */
		}
		dbexit();
		free_bread_crumb();
		exit(0);
	}
#endif
	for (i = 1; i <= dbnumrets(dbproc); i++) {
		add_bread_crumb();
		retname = dbretname(dbproc, i);
		printf("ret name %d is %s\n", i, retname);
		rettype = dbrettype(dbproc, i);
		printf("ret type %d is %d\n", i, rettype);
		retlen = dbretlen(dbproc, i);
		printf("ret len %d is %d\n", i, retlen);
		dbconvert(dbproc, rettype, dbretdata(dbproc, i), retlen, SYBVARCHAR, (BYTE*) teststr, -1);
		printf("ret data %d is %s\n", i, teststr);
		add_bread_crumb();
	}
	if ((retname == NULL) || strcmp(retname, "@b")) {
		fprintf(stdout, "Was expecting a retname to be @b.\n");
		exit(1);
	}
	if (strcmp(teststr, "42")) {
		fprintf(stdout, "Was expecting a retdata to be 42.\n");
		exit(1);
	}
	if (rettype != SYBINT4) {
		fprintf(stdout, "Was expecting a rettype to be SYBINT4 was %d.\n", rettype);
		exit(1);
	}
	if (retlen != 4) {
		fprintf(stdout, "Was expecting a retlen to be 4.\n");
		exit(1);
	}

	fprintf(stdout, "Dropping proc\n");
	add_bread_crumb();
	dbcmd(dbproc, "drop proc t0022");
	add_bread_crumb();
	dbsqlexec(dbproc);
	add_bread_crumb();
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}
	
	/*
	 * Chapter 2: test for resultsets containing only a return status
	 */
	
	fprintf(stdout, "Dropping proc t0022a\n");
	dbcmd(dbproc, "if object_id('t0022a') is not null drop proc t0022a");

	dbsqlexec(dbproc);

	while ((erc = dbresults(dbproc)) == SUCCEED) {
		fprintf(stdout, "dbresult succeeded dropping procedure\n");
		while ((erc = dbnextrow(dbproc)) == SUCCEED) {
			fprintf(stdout, "dbnextrow returned spurious rows dropping procedure\n");
			assert(0); /* dropping a procedure returns no rows */
		}
		assert(erc == NO_MORE_ROWS);
	}
	assert(erc == NO_MORE_RESULTS);

	fprintf(stdout, "creating proc t0022a\n");
	dbcmd(dbproc, "create proc t0022a (@b int) as\nreturn @b\n");
	if (dbsqlexec(dbproc) == FAIL) {
		fprintf(stdout, "Failed to create proc t0022a.\n");
		exit(1);
	}
	while ((erc = dbresults(dbproc)) != NO_MORE_RESULTS) {
		assert(erc != FAIL);
		while ((erc = dbnextrow(dbproc)) == SUCCEED) {
			assert(0); /* creating a procedure returns no rows */
		}
		assert(erc == NO_MORE_ROWS);
	}

	sprintf(cmd, "exec t0022a 17 exec t0022a 1024\n");
	fprintf(stdout, "%s\n", cmd);
	dbcmd(dbproc, cmd);
	dbsqlexec(dbproc);

	for (i=1; (erc = dbresults(dbproc)) != NO_MORE_RESULTS; i++) {
		enum {expected_iterations = 2};
		DBBOOL fret;
		DBINT  status;
		if (erc == FAIL) {
			fprintf(stdout, "t0022a failed for some reason.\n");
			exit(1);
		}
		printf("procedure returned %srows\n", DBROWS(dbproc)==SUCCEED? "" : "no ");
		while ((erc = dbnextrow(dbproc)) == SUCCEED) {
			assert(0); /* procedure returns no rows */
		}
		assert(erc == NO_MORE_ROWS);
		
		fret = dbhasretstat(dbproc);
		printf("procedure has %sreturn status\n", fret==TRUE? "" : "no ");
		assert(fret == TRUE);
		
		status = dbretstatus(dbproc);
		printf("return status %d is %d\n", i, (int) status);
		switch (i) {
		case 1: assert(status == 17); break;
		case 2: assert(status == 1024); break;
		default: assert(i <= expected_iterations);
		}
		
	}

	assert(erc == NO_MORE_RESULTS);
	
	fprintf(stdout, "Dropping proc t0022a\n");
	dbcmd(dbproc, "drop proc t0022a");
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}
	
	/* end chapter 2 */


	add_bread_crumb();
	dbexit();
	add_bread_crumb();

	fprintf(stdout, "dblib %s on %s\n", (failed ? "failed!" : "okay"), __FILE__);
	free_bread_crumb();
	return failed ? 1 : 0;
}
Exemplo n.º 14
0
static int
login_to_databases(BCPPARAMDATA * pdata, DBPROCESS ** dbsrc, DBPROCESS ** dbdest)
{
	LOGINREC *slogin;
	LOGINREC *dlogin;

	/* Initialize DB-Library. */

	if (dbinit() == FAIL)
		return FALSE;

	/*
	 * Install the user-supplied error-handling and message-handling
	 * routines. They are defined at the bottom of this source file.
	 */

	dberrhandle(err_handler);
	dbmsghandle(msg_handler);

	/*
	 * Allocate and initialize the LOGINREC structure to be used
	 * to open a connection to SQL Server.
	 */

	slogin = dblogin();

	DBSETLUSER(slogin, pdata->suser);
	DBSETLPWD(slogin, pdata->spass);
	DBSETLAPP(slogin, "Migrate Data");

	/* if packet size specified, set in login record */

	if (pdata->pflag && pdata->packetsize > 0) {
		DBSETLPACKET(slogin, pdata->packetsize);
	}

	/*
	 * Get a connection to the database.
	 */

	if ((*dbsrc = dbopen(slogin, pdata->sserver)) == (DBPROCESS *) NULL) {
		fprintf(stderr, "Can't connect to source server.\n");
		return FALSE;
	}

	if (dbuse(*dbsrc, pdata->sdb) == FAIL) {
		fprintf(stderr, "Can't change database to %s .\n", pdata->sdb);
		return FALSE;
	}

	dlogin = dblogin();

	DBSETLUSER(dlogin, pdata->duser);
	DBSETLPWD(dlogin, pdata->dpass);
	DBSETLAPP(dlogin, "Migrate Data");

	/* Enable bulk copy for this connection. */

	BCP_SETL(dlogin, TRUE);

	/* if packet size specified, set in login record */

	if (pdata->pflag && pdata->packetsize > 0) {
		DBSETLPACKET(dlogin, pdata->packetsize);
	}

	/*
	 * Get a connection to the database.
	 */

	if ((*dbdest = dbopen(dlogin, pdata->dserver)) == (DBPROCESS *) NULL) {
		fprintf(stderr, "Can't connect to destination server.\n");
		return FALSE;
	}

	if (dbuse(*dbdest, pdata->ddb) == FAIL) {
		fprintf(stderr, "Can't change database to %s .\n", pdata->sdb);
		return FALSE;
	}

	return TRUE;

}
Exemplo n.º 15
0
static int
test(int close_socket)
{
	LOGINREC *login;
	DBPROCESS *dbproc;
	RETCODE ret;
	int expected_error = -1;

	printf("Starting %s\n", UNITTEST);

	dbinit();

	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	printf("About to logon\n");

	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "t0020");

	printf("About to open\n");

	dbproc = dbopen(login, SERVER);
	dbsetuserdata(dbproc, (BYTE*) &expected_error);
	if (strlen(DATABASE))
		dbuse(dbproc, DATABASE);
	dbloginfree(login);

	dbcmd(dbproc, "select * from sysobjects");
	printf("dbsqlexec should not hang.\n");

	ret = dbsettime(15);
	if (ret != SUCCEED) {
		fprintf(stderr, "Failed.  Error setting timeout.\n");
		return 1;
	}

	if (!shutdown_socket(dbproc)) {
		fprintf(stderr, "Error shutting down connection\n");
		return 1;
	}
	if (close_socket)
		close(end_socket);

	alarm(20);
	expected_error = close_socket ? 20006 : 20003;
	ret = dbsqlexec(dbproc);
	alarm(0);
	if (ret != FAIL) {
		fprintf(stderr, "Failed.  Expected FAIL to be returned.\n");
		return 1;
	}

	dbsetuserdata(dbproc, NULL);
	if (!close_socket)
		close(end_socket);
	dbexit();

	printf("dblib okay on %s\n", __FILE__);
	return 0;
}
Exemplo n.º 16
0
int
main(int argc, char **argv)
{
	const int rows_to_add = 50;
	LOGINREC *login;
	DBPROCESS *dbproc;
	int i, expected_error;
	char *s, teststr[1024];
	DBINT testint;
	int failed = 0;

	set_malloc_options();

	read_login_info(argc, argv);

	printf("Starting %s\n", argv[0]);

	dbinit();

	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	printf("About to logon\n");

	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "t0004");

	printf("About to open\n");

	dbproc = dbopen(login, SERVER);
	if (strlen(DATABASE))
		dbuse(dbproc, DATABASE);
	dbloginfree(login);

	printf("creating table\n");
	sql_cmd(dbproc);
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}

	printf("insert\n");
	for (i = 1; i < rows_to_add; i++) {
		sql_cmd(dbproc);
		dbsqlexec(dbproc);
		while (dbresults(dbproc) != NO_MORE_RESULTS) {
			/* nop */
		}
	}

	sql_cmd(dbproc); /* select */
	dbsqlexec(dbproc);

	if (dbresults(dbproc) != SUCCEED) {
		printf("Was expecting a result set.");
		exit(1);
	}

	for (i = 1; i <= dbnumcols(dbproc); i++)
		printf("col %d is %s\n", i, dbcolname(dbproc, i));

	dbbind(dbproc, 1, INTBIND, 0, (BYTE *) & testint);
	dbbind(dbproc, 2, STRINGBIND, 0, (BYTE *) teststr);

	for (i = 1; i <= 24; i++) {
	char expected[1024];

		sprintf(expected, "row %04d", i);

		if (i % 5 == 0) {
			dbclrbuf(dbproc, 5);
		}


		testint = -1;
		strcpy(teststr, "bogus");

		if (REG_ROW != dbnextrow(dbproc)) {
			fprintf(stderr, "Failed.  Expected a row\n");
			exit(1);
		}
		if (testint != i) {
			fprintf(stderr, "Failed.  Expected i to be %d, was %d\n", i, (int) testint);
			abort();
		}
		if (0 != strncmp(teststr, expected, strlen(expected))) {
			printf("Failed.  Expected s to be |%s|, was |%s|\n", expected, teststr);
			abort();
		}
		printf("Read a row of data -> %d %s\n", (int) testint, teststr);
	}



	printf("second select\n");
	printf("testing dbgetchar...\n");
	for (i=0; (s = dbgetchar(dbproc, i)) != NULL; i++) {
		putchar(*s);
		if (!(isprint((unsigned char)*s) || iscntrl((unsigned char)*s))) {
			fprintf(stderr, "%s:%d: dbgetchar failed with %x at position %d\n", __FILE__, __LINE__, *s, i);
			failed = 1;
			break;
		}
	}
	printf("<== end of command buffer\n");

	if (SUCCEED != sql_cmd(dbproc)) {
		fprintf(stderr, "%s:%d: dbcmd failed\n", __FILE__, __LINE__);
		failed = 1;
	}
	printf("About to exec for the second time.  Should fail\n");
	expected_error = 20019;
	dbsetuserdata(dbproc, (BYTE*) &expected_error);
	if (FAIL != dbsqlexec(dbproc)) {
		fprintf(stderr, "%s:%d: dbsqlexec should have failed but didn't\n", __FILE__, __LINE__);
		failed = 1;
	}
	dbexit();

	printf("%s %s\n", __FILE__, (failed ? "failed!" : "OK"));
	return failed ? 1 : 0;
}
Exemplo n.º 17
0
int
main(int argc, char **argv)
{
	LOGINREC *login;
	DBPROCESS *dbproc;
	int i;
	char teststr[1024];
	DBINT testint;
	DBVARYBIN  testvbin;
	DBVARYCHAR testvstr;
	int failed = 0;
	int expected_error;

	set_malloc_options();

	read_login_info(argc, argv);

	fprintf(stdout, "Starting %s\n", argv[0]);

	dbinit();

	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	fprintf(stdout, "About to logon\n");

	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "t0007");

	fprintf(stdout, "About to open\n");

	dbproc = dbopen(login, SERVER);
	if (strlen(DATABASE))
		dbuse(dbproc, DATABASE);
	dbloginfree(login);

	create_tables(dbproc, 10);

	if (!start_query(dbproc)) {
		fprintf(stderr, "%s:%d: start_query failed\n", __FILE__, __LINE__);
		failed = 1;
	}

	dbbind(dbproc, 1, INTBIND, 0, (BYTE *) & testint);
	dbbind(dbproc, 2, STRINGBIND, 0, (BYTE *) teststr);

	for (i = 1; i <= 2; i++) {
		char expected[1024];

		sprintf(expected, "row %07d", i);

		if (i % 5 == 0) {
			dbclrbuf(dbproc, 5);
		}

		testint = -1;
		strcpy(teststr, "bogus");

		if (REG_ROW != dbnextrow(dbproc)) {
			fprintf(stderr, "Failed.  Expected a row\n");
			abort();
		}
		if (testint != i) {
			fprintf(stderr, "Failed.  Expected i to be %d, was %d\n", i, (int) testint);
			abort();
		}
		if (0 != strncmp(teststr, expected, strlen(expected))) {
			fprintf(stdout, "Failed.  Expected s to be |%s|, was |%s|\n", expected, teststr);
			abort();
		}
		printf("Read a row of data -> %d %s\n", (int) testint, teststr);
	}


	fprintf(stdout, "second select.  Should fail.\n");

	expected_error = 20019;
	dbsetuserdata(dbproc, (BYTE*) &expected_error);

	if (start_query(dbproc)) {
		fprintf(stderr, "%s:%d: start_query should have failed but didn't\n", __FILE__, __LINE__);
		failed = 1;
	}

	dbcancel(dbproc);
	
	/* 
	 * Test Binary binding
	 */
	if (!start_query(dbproc)) {
		fprintf(stderr, "%s:%d: start_query failed\n", __FILE__, __LINE__);
		failed = 1;
	}

	dbbind(dbproc, 1, VARYBINBIND, sizeof(testvbin), (BYTE *) &testvbin);
	dbbind(dbproc, 2, VARYCHARBIND, sizeof(testvstr), (BYTE *) &testvstr);
	dbbind(dbproc, 3, BINARYBIND, sizeof(testint), (BYTE *) &testint);

	for (i = 1; i <= 2; i++) {
		char expected[1024];

		sprintf(expected, "row %07d ", i);

		testint = -1;
		memset(&testvbin, '*', sizeof(testvbin));
		memset(&testvstr, '*', sizeof(testvstr));

		if (REG_ROW != dbnextrow(dbproc)) {
			fprintf(stderr, "Failed.  Expected a row\n");
			abort();
		}
		if (testint != i) {
			fprintf(stderr, "Failed, line %d.  Expected i to be %d, was %d (0x%x)\n", __LINE__, i, (int) testint, (int) testint);
			abort();
		}
		if (testvbin.len != sizeof(testint)) {
			fprintf(stderr, "Failed, line %d.  Expected bin lenght to be %d, was %d\n", __LINE__, (int) sizeof(testint), (int) testvbin.len);
			abort();
		}
		memcpy(&testint, testvbin.array, sizeof(testint));
		if (testint != i) {
			fprintf(stderr, "Failed, line %d.  Expected i to be %d, was %d (0x%x)\n", __LINE__, i, (int) testint, (int) testint);
			abort();
		}
		if (testvstr.len != strlen(expected) || 0 != strncmp(testvstr.str, expected, strlen(expected))) {
			fprintf(stdout, "Failed, line %d.  Expected s to be |%s|, was |%s|\n", __LINE__, expected, testvstr.str);
			abort();
		}
		testvstr.str[testvstr.len] = 0;
		printf("Read a row of data -> %d %s\n", (int) testint, testvstr.str);
	}


	dbexit();

	fprintf(stdout, "%s %s\n", __FILE__, (failed ? "failed!" : "OK"));
	return failed ? 1 : 0;
}
Exemplo n.º 18
0
int
main(int argc, char **argv)
{
	LOGINREC *login;
	DBPROCESS *dbproc;
	int i;
	DBINT testint = -1;

	read_login_info(argc, argv);

	printf("Starting %s\n", argv[0]);

	dbinit();

	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	printf("About to logon\n");

	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "pending");

	printf("About to open\n");

	dbproc = dbopen(login, SERVER);
	if (strlen(DATABASE))
		dbuse(dbproc, DATABASE);
	dbloginfree(login);


	/* first query, start transactions */
	sql_cmd(dbproc);
	dbsqlexec(dbproc);

	/* second query, select */
	printf("second select\n");

	if (SUCCEED != sql_cmd(dbproc) || SUCCEED != dbsqlexec(dbproc)) {
		fprintf(stderr, "%s:%d: dbcmd failed\n", __FILE__, __LINE__);
		exit(1);
	}

	if (dbresults(dbproc) != SUCCEED) {
		fprintf(stderr, "Was expecting a result set.");
		exit(1);
	}

	for (i = 1; i <= dbnumcols(dbproc); i++)
		printf("col %d is %s\n", i, dbcolname(dbproc, i));

	dbbind(dbproc, 1, INTBIND, 0, (BYTE *) & testint);

	if (REG_ROW != dbnextrow(dbproc)) {
		fprintf(stderr, "Failed.  Expected a row\n");
		exit(1);
	}
	if (testint != 634) {
		fprintf(stderr, "Failed.  Expected i to be %d, was %d\n", i, (int) testint);
		exit(1);
	}
	if (dbnextrow(dbproc) != NO_MORE_ROWS) {
		fprintf(stderr, "No other rows expected\n");
	}

	/* third query, commit */
	if (SUCCEED != sql_cmd(dbproc)) {
		fprintf(stderr, "%s:%d: dbcmd failed\n", __FILE__, __LINE__);
		exit(1);
	}

	while (dbresults(dbproc) != NO_MORE_RESULTS)
		continue;

	dbexit();

	printf("ok\n");
	return 0;
}
Exemplo n.º 19
0
int
main(int argc, char **argv)
{
	LOGINREC *login;
	DBINT db_i;
	RETCODE ret;
	
	read_login_info(argc, argv);

	printf("Start\n");
	dbinit();

	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "setnull");


	printf("About to open %s.%s\n", SERVER, DATABASE);

	dbproc = dbopen(login, SERVER);
	if (strlen(DATABASE))
		dbuse(dbproc, DATABASE);
	dbloginfree(login);

	/* try to set an int */
	db_i = 0xdeadbeef;
	ret = dbsetnull(dbproc, INTBIND, 0, (BYTE *) &db_i);
	if (ret != SUCCEED) {
		fprintf(stderr, "dbsetnull returned error %d\n", (int) ret);
		failed = 1;
	}

	ret = dbsetnull(dbproc, INTBIND, 1, (BYTE *) &db_i);
	if (ret != SUCCEED) {
		fprintf(stderr, "dbsetnull returned error %d\n", (int) ret);
		failed = 1;
	}

	/* check result */
	db_i = 0;
	dbcmd(dbproc, "select convert(int, null)");

	dbsqlexec(dbproc);

	if (dbresults(dbproc) != SUCCEED) {
		fprintf(stderr, "Was expecting a row.\n");
		failed = 1;
		dbcancel(dbproc);
	}

	dbbind(dbproc, 1, INTBIND, 0, (BYTE *) &db_i);
	printf("db_i = %ld\n", (long int) db_i);

	if (dbnextrow(dbproc) != REG_ROW) {
		fprintf(stderr, "Was expecting a row.\n");
		failed = 1;
		dbcancel(dbproc);
	}
	printf("db_i = %ld\n", (long int) db_i);

	if (dbnextrow(dbproc) != NO_MORE_ROWS) {
		fprintf(stderr, "Only one row expected\n");
		dbcancel(dbproc);
		failed = 1;
	}

	while (dbresults(dbproc) == SUCCEED) {
		/* nop */
	}

	if (db_i != 0xdeadbeef) {
		fprintf(stderr, "Invalid NULL %ld returned (%s:%d)\n", (long int) db_i, tds_basename(__FILE__), __LINE__);
		failed = 1;
	}

	/* try if dbset null consider length */
	for (db_i = 1; db_i > 0; db_i <<= 1) {
		printf("db_i = %ld\n", (long int) db_i);
		ret = dbsetnull(dbproc, INTBIND, db_i, (BYTE *) &db_i);
		if (ret != SUCCEED) {
			fprintf(stderr, "dbsetnull returned error %d for bindlen %ld\n", (int) ret, (long int) db_i);
			failed = 1;
			break;
		}
	}

	char_test(NULL, -1, "123456");
	char_test(NULL, 0,  "123456");
	char_test(NULL, 2,  "  3456");

	char_test("foo", -1,  "foo456");
	char_test("foo", 0,   "foo456");
/*	char_test("foo", 2,   ""); */
	char_test("foo", 5,   "foo  6");

	char_test("foo ", -1,  "foo 56");
	char_test("foo ", 0,   "foo 56");
/*	char_test("foo ", 2,   ""); */
	char_test("foo ", 5,   "foo  6");

	char_test("foo ", 10,  "foo       _____");

	printf("dblib %s on %s\n", (failed ? "failed!" : "okay"), __FILE__);
	dbexit();

	return failed ? 1 : 0;
}
Exemplo n.º 20
0
int
main(int argc, char **argv)
{
	LOGINREC *login;
	DBPROCESS *dbproc;
	int i;
	char teststr[1024];
	DBINT testint;

	set_malloc_options();

	read_login_info();

	fprintf(stdout, "Start\n");
	add_bread_crumb();

	/* Fortify_EnterScope(); */
	dbinit();

	add_bread_crumb();
	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	fprintf(stdout, "About to logon\n");

	add_bread_crumb();
	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "t0010");
	DBSETLHOST(login, "ntbox.dntis.ro");

	fprintf(stdout, "About to open\n");

	add_bread_crumb();
	dbproc = dbopen(login, SERVER);
	if (strlen(DATABASE))
		dbuse(dbproc, DATABASE);
	add_bread_crumb();

#ifdef MICROSOFT_DBLIB
	dbsetopt(dbproc, DBBUFFER, "100");
#else
	dbsetopt(dbproc, DBBUFFER, "100", 0);
#endif
	add_bread_crumb();

	fprintf(stdout, "Dropping table\n");
	add_bread_crumb();
	dbcmd(dbproc, "drop table #dblib0010");
	add_bread_crumb();
	dbsqlexec(dbproc);
	add_bread_crumb();
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}
	add_bread_crumb();

	fprintf(stdout, "creating table\n");
	dbcmd(dbproc, "create table #dblib0010 (i int not null, s char(10) not null)");
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}

	fprintf(stdout, "insert\n");
	dbcmd(dbproc, "insert into #dblib0010 values (1, 'abcdef')");
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}
	dbcmd(dbproc, "insert into #dblib0010 values (2, 'abc')");
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}


	fprintf(stdout, "select\n");
	dbcmd(dbproc, "select * from #dblib0010 order by i");
	dbsqlexec(dbproc);
	add_bread_crumb();


	if (dbresults(dbproc) != SUCCEED) {
		add_bread_crumb();
		fprintf(stdout, "Was expecting a result set.");
		exit(1);
	}
	add_bread_crumb();

	for (i = 1; i <= dbnumcols(dbproc); i++) {
		add_bread_crumb();
		printf("col %d is %s\n", i, dbcolname(dbproc, i));
		add_bread_crumb();
	}

	add_bread_crumb();
	dbbind(dbproc, 1, INTBIND, -1, (BYTE *) & testint);
	add_bread_crumb();
	dbbind(dbproc, 2, STRINGBIND, 0, (BYTE *) teststr);
	add_bread_crumb();

	add_bread_crumb();


	if (REG_ROW != dbnextrow(dbproc)) {
		fprintf(stderr, "dblib failed for %s\n", __FILE__);
		exit(1);
	}
	if (0 != strcmp("abcdef    ", teststr)) {
		fprintf(stderr, "Expected |%s|, found |%s|\n", "abcdef", teststr);
		fprintf(stderr, "dblib failed for %s\n", __FILE__);
		exit(1);
	}

	if (REG_ROW != dbnextrow(dbproc)) {
		fprintf(stderr, "dblib failed for %s\n", __FILE__);
		exit(1);
	}
	if (0 != strcmp("abc       ", teststr)) {
		fprintf(stderr, "Expected |%s|, found |%s|\n", "abc", teststr);
		fprintf(stderr, "dblib failed for %s\n", __FILE__);
		exit(1);
	}

	fprintf(stderr, "dblib passed for %s\n", __FILE__);
	return 0;
}
Exemplo n.º 21
0
int
main(int argc, char **argv)
{
	RETCODE rc;
	const int rows_to_add = 50;
	LOGINREC *login;
	DBPROCESS *dbproc;
	int i;

	set_malloc_options();

	read_login_info(argc, argv);
	fprintf(stdout, "Starting %s\n", argv[0]);

	/* Fortify_EnterScope(); */
	dbinit();

	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	fprintf(stdout, "About to logon\n");

	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "t0006");
	DBSETLHOST(login, "ntbox.dntis.ro");

	fprintf(stdout, "About to open\n");

	dbproc = dbopen(login, SERVER);
	if (strlen(DATABASE))
		dbuse(dbproc, DATABASE);
	dbloginfree(login);

#ifdef MICROSOFT_DBLIB
	dbsetopt(dbproc, DBBUFFER, "5000");
#else
	dbsetopt(dbproc, DBBUFFER, "5000", 0);
#endif

	fprintf(stdout, "creating table\n");
	sql_cmd(dbproc);
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}

	fprintf(stdout, "insert\n");
	for (i = 1; i < rows_to_add; i++) {
		sql_cmd(dbproc);
		dbsqlexec(dbproc);
		while (dbresults(dbproc) != NO_MORE_RESULTS) {
			/* nop */
		}
	}

	fprintf(stdout, "first select\n");
	if (SUCCEED != sql_cmd(dbproc)) {
		fprintf(stderr, "%s:%d: dbcmd failed\n", __FILE__, __LINE__);
		failed = 1;
	}
	if (SUCCEED != dbsqlexec(dbproc)) {
		fprintf(stderr, "%s:%d: dbsqlexec failed\n", __FILE__, __LINE__);
		failed = 1;
	}


	if (dbresults(dbproc) != SUCCEED) {
		fprintf(stdout, "%s:%d: Was expecting a result set.", __FILE__, __LINE__);
		failed = 1;
		exit(1);
	}

	for (i = 1; i <= dbnumcols(dbproc); i++)
		printf("col %d is %s\n", i, dbcolname(dbproc, i));

	dbbind(dbproc, 1, INTBIND, 0, (BYTE *) & testint);
	dbbind(dbproc, 2, STRINGBIND, 0, (BYTE *) teststr);

	get_results(dbproc, 1);

	testint = -1;
	strcpy(teststr, "bogus");
	fprintf(stdout, "second select\n");
	sql_cmd(dbproc);
	dbsqlexec(dbproc);

	if ((rc = dbresults(dbproc)) != SUCCEED) {
		fprintf(stdout, "%s:%d: Was expecting a result set. (rc=%d)\n", __FILE__, __LINE__, rc);
		failed = 1;
	}

	if (!failed) {
		dbbind(dbproc, 1, INTBIND, 0, (BYTE *) & testint);
		dbbind(dbproc, 2, STRINGBIND, 0, (BYTE *) teststr);

		get_results(dbproc, 25);
	}
	dbexit();

	fprintf(stdout, "%s %s\n", __FILE__, (failed ? "failed!" : "OK"));
	return failed ? 1 : 0;
}
Exemplo n.º 22
0
static int pdo_dblib_handle_factory(pdo_dbh_t *dbh, zval *driver_options)
{
	pdo_dblib_db_handle *H;
	int i, nvars, nvers, ret = 0;

	const pdo_dblib_keyval tdsver[] = {
		 {"4.2",DBVERSION_42}
		,{"4.6",DBVERSION_46}
		,{"5.0",DBVERSION_70} /* FIXME: This does not work with Sybase, but environ will */
		,{"6.0",DBVERSION_70}
		,{"7.0",DBVERSION_70}
#ifdef DBVERSION_71
		,{"7.1",DBVERSION_71}
#endif
#ifdef DBVERSION_72
		,{"7.2",DBVERSION_72}
		,{"8.0",DBVERSION_72}
#endif
#ifdef DBVERSION_73
		,{"7.3",DBVERSION_73}
#endif
#ifdef DBVERSION_74
		,{"7.4",DBVERSION_74}
#endif
		,{"10.0",DBVERSION_100}
		,{"auto",0} /* Only works with FreeTDS. Other drivers will bork */

	};
	
	struct pdo_data_src_parser vars[] = {
		{ "charset",	NULL,	0 }
		,{ "appname",	"PHP " PDO_DBLIB_FLAVOUR,	0 }
		,{ "host",		"127.0.0.1", 0 }
		,{ "dbname",	NULL,	0 }
		,{ "secure",	NULL,	0 } /* DBSETLSECURE */
		,{ "version",	NULL,	0 } /* DBSETLVERSION */
	};

	nvars = sizeof(vars)/sizeof(vars[0]);
	nvers = sizeof(tdsver)/sizeof(tdsver[0]);
	
	php_pdo_parse_data_source(dbh->data_source, dbh->data_source_len, vars, nvars);

	H = pecalloc(1, sizeof(*H), dbh->is_persistent);
	H->login = dblogin();
	H->err.sqlstate = dbh->error_code;
	H->stringify_uniqueidentifier = 0;

	if (!H->login) {
		goto cleanup;
	}

	if (driver_options) {
		int connect_timeout = pdo_attr_lval(driver_options, PDO_DBLIB_ATTR_CONNECTION_TIMEOUT, -1);
		int query_timeout = pdo_attr_lval(driver_options, PDO_DBLIB_ATTR_QUERY_TIMEOUT, -1);
		int timeout = pdo_attr_lval(driver_options, PDO_ATTR_TIMEOUT, 30);

		if (connect_timeout == -1) {
			connect_timeout = timeout;
		}
		if (query_timeout == -1) {
			query_timeout = timeout;
		}

		dbsetlogintime(connect_timeout); /* Connection/Login Timeout */
		dbsettime(query_timeout); /* Statement Timeout */

		H->stringify_uniqueidentifier = pdo_attr_lval(driver_options, PDO_DBLIB_ATTR_STRINGIFY_UNIQUEIDENTIFIER, 0);
	}

	DBERRHANDLE(H->login, (EHANDLEFUNC) pdo_dblib_error_handler);
	DBMSGHANDLE(H->login, (MHANDLEFUNC) pdo_dblib_msg_handler);

	if(vars[5].optval) {
		for(i=0;i<nvers;i++) {
			if(strcmp(vars[5].optval,tdsver[i].key) == 0) {
				if(FAIL==dbsetlversion(H->login, tdsver[i].value)) {
					pdo_raise_impl_error(dbh, NULL, "HY000", "PDO_DBLIB: Failed to set version specified in connection string.");
					goto cleanup;
				}
				break;
			}
		}

		if (i==nvers) {
			printf("Invalid version '%s'\n", vars[5].optval);
			pdo_raise_impl_error(dbh, NULL, "HY000", "PDO_DBLIB: Invalid version specified in connection string.");
			goto cleanup; /* unknown version specified */
		}
	}

	if (dbh->username) {
		if(FAIL == DBSETLUSER(H->login, dbh->username)) {
			goto cleanup;
		}
	}

	if (dbh->password) {
		if(FAIL == DBSETLPWD(H->login, dbh->password)) {
			goto cleanup;
		}
	}

#if !PHP_DBLIB_IS_MSSQL
	if (vars[0].optval) {
		DBSETLCHARSET(H->login, vars[0].optval);
	}
#endif

	DBSETLAPP(H->login, vars[1].optval);

/* DBSETLDBNAME is only available in FreeTDS 0.92 or above */
#ifdef DBSETLDBNAME
	if (vars[3].optval) {
		if(FAIL == DBSETLDBNAME(H->login, vars[3].optval)) goto cleanup;
	}
#endif

	H->link = dbopen(H->login, vars[2].optval);

	if (!H->link) {
		goto cleanup;
	}

/*
 * FreeTDS < 0.92 does not support the DBSETLDBNAME option
 * Send use database here after login (Will not work with SQL Azure)
 */
#ifndef DBSETLDBNAME
	if (vars[3].optval) {
		if(FAIL == dbuse(H->link, vars[3].optval)) goto cleanup;
	}
#endif

#if PHP_DBLIB_IS_MSSQL
	/* dblib do not return more than this length from text/image */
	DBSETOPT(H->link, DBTEXTLIMIT, "2147483647");
#endif

	/* limit text/image from network */
	DBSETOPT(H->link, DBTEXTSIZE, "2147483647");

	/* allow double quoted indentifiers */
	DBSETOPT(H->link, DBQUOTEDIDENT, "1");

	ret = 1;
	dbh->max_escaped_char_length = 2;
	dbh->alloc_own_columns = 1;

cleanup:
	for (i = 0; i < nvars; i++) {
		if (vars[i].freeme) {
			efree(vars[i].optval);
		}
	}

	dbh->methods = &dblib_methods;
	dbh->driver_data = H;

	if (!ret) {
		zend_throw_exception_ex(php_pdo_get_exception(), DBLIB_G(err).dberr,
			"SQLSTATE[%s] %s (severity %d)",
			DBLIB_G(err).sqlstate,
			DBLIB_G(err).dberrstr,
			DBLIB_G(err).severity);
	}

	return ret;
}
Exemplo n.º 23
0
LOGINREC *
get_login(int argc, char *argv[], OPTIONS *options)
{
	LOGINREC *login;
	int ch;
	char *username = NULL, *password = NULL;

	extern char *optarg;

	assert(options && argv);
	
	options->appname = tds_basename(argv[0]);
	options->colsep = default_colsep; /* may be overridden by -t */
	
	login = dblogin();
	
	if (!login) {
		fprintf(stderr, "%s: unable to allocate login structure\n", options->appname);
		exit(1);
	}
	
	DBSETLAPP(login, options->appname);
	
	options->servername = getenv("DSQUERY");
	
	while ((ch = getopt(argc, argv, "U:P:R:S:dD:i:o:e:t:H:hqv")) != -1) {
		switch (ch) {
		case 'U':
			username = strdup(optarg);
			break;
		case 'R': 
			  parse_pivot_description(options, optarg);
			  break;
		case 'P':
			password = getpassarg(optarg);
			break;
		case 'S':
			options->servername = strdup(optarg);
			break;
		case 'd':
		case 'D':
			options->database = strdup(optarg);
			break;
		case 'i':
			options->input_filename = strdup(optarg);
			break;
		case 'o':
			options->output_filename = strdup(optarg);
			break;
		case 'e':
			options->error_filename = strdup(optarg);
			break;
		case 't':
			unescape(optarg);
			options->colsep = strdup(optarg);
			break;
		case 'h':
			options->headers = stdout;
			break;
		case 'H':
			strcpy(options->hostname, optarg);
			break;
		case 'q':
			options->fquiet = 1;
			break;
		case 'v':
			options->fverbose = 1;
			break;
		case '?':
		default:
			usage(options->appname);
			exit(1);
		}
	}

	if (username) 
		DBSETLUSER(login, username);
	

	if( !options->hostname[0] ) {
		if (-1 == gethostname(options->hostname, sizeof(options->hostname))) {
			perror("unable to get hostname");
		}
	}

	if( options->hostname[0] ) {
		DBSETLHOST(login, options->hostname);
	}

	/* Look for a password if a username was provided, else assume domain login */
	if (password) {
		DBSETLPWD(login, password);
		memset(password, 0, strlen(password));
	} else if (username) {
		char password[128];

		readpassphrase("Password: ", password, sizeof(password), RPP_ECHO_OFF);
		DBSETLPWD(login, password);
        }

	if (!options->servername) {
		usage(options->appname);
		exit(1);
	}
	
	return login;
}
Exemplo n.º 24
0
int
main(int argc, char **argv)
{
	const int rows_to_add = 48;
	LOGINREC *login;
	DBPROCESS *dbproc;
	int i;
	char teststr[1024];
	DBINT testint;
	DBINT last_read = -1;

	set_malloc_options();

	read_login_info(argc, argv);

	fprintf(stdout, "Starting %s\n", argv[0]);

	/* Fortify_EnterScope(); */
	dbinit();

	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	fprintf(stdout, "About to logon\n");

	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "t0008");
	DBSETLHOST(login, "ntbox.dntis.ro");

	fprintf(stdout, "About to open\n");

	dbproc = dbopen(login, SERVER);
	if (strlen(DATABASE))
		dbuse(dbproc, DATABASE);
	dbloginfree(login);

#ifdef MICROSOFT_DBLIB
	dbsetopt(dbproc, DBBUFFER, "25");
#else
	dbsetopt(dbproc, DBBUFFER, "25", 0);
#endif

	fprintf(stdout, "creating table\n");
	dbcmd(dbproc, "create table #dblib0008 (i int not null, s char(10) not null)");
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}

	fprintf(stdout, "insert\n");
	for (i = 1; i <= rows_to_add; i++) {
	char cmd[1024];

		sprintf(cmd, "insert into #dblib0008 values (%d, 'row %03d')", i, i);
		dbcmd(dbproc, cmd);
		dbsqlexec(dbproc);
		while (dbresults(dbproc) != NO_MORE_RESULTS) {
			/* nop */
		}
	}

	fprintf(stdout, "select\n");
	dbcmd(dbproc, "select * from #dblib0008 order by i");
	dbsqlexec(dbproc);

	if (dbresults(dbproc) != SUCCEED) {
		fprintf(stdout, "Was expecting a result set.");
		exit(1);
	}

	for (i = 1; i <= dbnumcols(dbproc); i++)
		printf("col %d is %s\n", i, dbcolname(dbproc, i));

	dbbind(dbproc, 1, INTBIND, 0, (BYTE *) & testint);
	dbbind(dbproc, 2, STRINGBIND, 0, (BYTE *) teststr);

	for (i = 1; i <= rows_to_add; i++) {
	char expected[1024];

		sprintf(expected, "row %03d", i);

		if (i % 25 == 0) {
			dbclrbuf(dbproc, 25);
		}

		if (REG_ROW != dbnextrow(dbproc)) {
			fprintf(stderr, "dblib failed for %s, dbnextrow1\n", __FILE__);
			dbexit();
			return 1;
		}
		last_read = testint;
		if (testint < 1 || testint > rows_to_add) {
			fprintf(stderr, "dblib failed for %s testint = %d\n", __FILE__, (int) testint);
			exit(1);
		}
		if (testint != i) {
			fprintf(stderr, "Failed.  Expected i to be %d, was %d\n", i, (int) testint);
			abort();
		}
		if (0 != strncmp(teststr, expected, strlen(expected))) {
			fprintf(stdout, "Failed.  Expected s to be |%s|, was |%s|\n", expected, teststr);
			abort();
		}
		printf("Read a row of data -> %d %s\n", (int) testint, teststr);
	}

	if (REG_ROW == dbnextrow(dbproc)) {
		fprintf(stderr, "dblib failed for %s, dbnextrow2\n", __FILE__);
		dbexit();
		return 1;
	}

	dbexit();

	fprintf(stdout, "%s %s (last_read: %d)\n", __FILE__, ((last_read != rows_to_add)? "failed!" : "OK"), (int) last_read);
	return (last_read == rows_to_add) ? 0 : 1;
}
Exemplo n.º 25
0
int
main(int argc, char **argv)
{
	LOGINREC *login;
	DBPROCESS *dbproc;
	int i;
	char teststr[1024];
	DBINT testint;

	set_malloc_options();

	read_login_info(argc, argv);

	printf("Starting %s\n", argv[0]);

	/* Fortify_EnterScope(); */
	dbinit();

	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	printf("About to logon\n");

	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "text_buffer");
	DBSETLHOST(login, "ntbox.dntis.ro");

	printf("About to open\n");

	dbproc = dbopen(login, SERVER);
	if (strlen(DATABASE))
		dbuse(dbproc, DATABASE);
	dbloginfree(login);

#ifdef MICROSOFT_DBLIB
	dbsetopt(dbproc, DBBUFFER, "100");
#else
	dbsetopt(dbproc, DBBUFFER, "100", 0);
#endif

	printf("creating table\n");
	sql_cmd(dbproc);
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}

	printf("insert\n");
	sql_cmd(dbproc);
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}
	sql_cmd(dbproc);
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}


	printf("select\n");
	dbcmd(dbproc, "select * from #dblib order by i");
	dbsqlexec(dbproc);

	if (dbresults(dbproc) != SUCCEED) {
		printf("Was expecting a result set.");
		return 1;
	}

	for (i = 1; i <= dbnumcols(dbproc); i++) {
		printf("col %d is %s\n", i, dbcolname(dbproc, i));
	}

	dbbind(dbproc, 1, INTBIND, 0, (BYTE *) & testint);
	dbbind(dbproc, 2, STRINGBIND, 0, (BYTE *) teststr);

	if (REG_ROW != dbnextrow(dbproc)) {
		fprintf(stderr, "dblib failed for %s:%d\n", __FILE__, __LINE__);
		return 1;
	}
	if (dbdatlen(dbproc, 2) != 6 || 0 != strcmp("ABCDEF", teststr)) {
		fprintf(stderr, "Expected |%s|, found |%s|\n", "ABCDEF", teststr);
		fprintf(stderr, "dblib failed for %s:%d\n", __FILE__, __LINE__);
		return 1;
	}

	if (REG_ROW != dbnextrow(dbproc)) {
		fprintf(stderr, "dblib failed for %s:%d\n", __FILE__, __LINE__);
		return 1;
	}
	if (dbdatlen(dbproc, 2) != 3 || 0 != strcmp("abc", teststr)) {
		fprintf(stderr, "Expected |%s|, found |%s|\n", "abc", teststr);
		fprintf(stderr, "dblib failed for %s:%d\n", __FILE__, __LINE__);
		return 1;
	}

	/* get again row 1 */
	dbgetrow(dbproc, 1);

	/* here length and string should be ok */
	if (dbdatlen(dbproc, 2) != 6 || 0 != strcmp("ABCDEF", teststr)) {
		fprintf(stderr, "Expected |%s|, found |%s|\n", "ABCDEF", teststr);
		fprintf(stderr, "dblib failed for %s:%d\n", __FILE__, __LINE__);
		return 1;
	}

	dbgetrow(dbproc, 2);
	if (dbdatlen(dbproc, 2) != 3 || 0 != strcmp("abc", teststr)) {
		fprintf(stderr, "Expected |%s|, found |%s|\n", "abc", teststr);
		fprintf(stderr, "dblib failed for %s:%d\n", __FILE__, __LINE__);
		return 1;
	}

	dbexit();

	printf("%s %s\n", __FILE__, (0 ? "failed!" : "OK"));
	return 0;
}
Exemplo n.º 26
0
static void
test(int bind_type)
{
	LOGINREC *login;
	DBPROCESS *dbproc;
	DBNUMERIC *num = NULL, *num2 = NULL;
	RETCODE ret;
	int i;

	sql_rewind();
	login = dblogin();

	DBSETLUSER(login, USER);
	DBSETLPWD(login, PASSWORD);
	DBSETLAPP(login, "numeric");
	dbsetmaxprocs(25);
	DBSETLHOST(login, SERVER);

	dbproc = dbopen(login, SERVER);
	dbloginfree(login);
	login = NULL;
	if (strlen(DATABASE))
		dbuse(dbproc, DATABASE);

	sql_cmd(dbproc);
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}

	sql_cmd(dbproc);
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}

	if (DBTDS_5_0 < DBTDS(dbproc)) {
		ret = dbcmd(dbproc,
			    "SET ARITHABORT ON;"
			    "SET CONCAT_NULL_YIELDS_NULL ON;"
			    "SET ANSI_NULLS ON;"
			    "SET ANSI_NULL_DFLT_ON ON;"
			    "SET ANSI_PADDING ON;"
			    "SET ANSI_WARNINGS ON;"
			    "SET ANSI_NULL_DFLT_ON ON;"
			    "SET CURSOR_CLOSE_ON_COMMIT ON;"
			    "SET QUOTED_IDENTIFIER ON");
		chk(ret, "dbcmd");
		ret = dbsqlexec(dbproc);
		chk(ret, "dbsqlexec");

		ret = dbcancel(dbproc);
		chk(ret, "dbcancel");
	}

	ret = dbrpcinit(dbproc, "testDecimal", 0);
	chk(ret, "dbrpcinit");

	num = (DBDECIMAL *) calloc(1, sizeof(DBDECIMAL));
	num->scale = 5;
	num->precision = 16;
	dbconvert(dbproc, SYBVARCHAR, (const BYTE *) "123.45", -1, SYBDECIMAL, (BYTE *) num, sizeof(*num));

	ret = dbrpcparam(dbproc, "@idecimal", 0, SYBDECIMAL, -1, sizeof(DBDECIMAL), (BYTE *) num);
	chk(ret, "dbrpcparam");
	ret = dbrpcsend(dbproc);
	chk(ret, "dbrpcsend");
	ret = dbsqlok(dbproc);
	chk(ret, "dbsqlok");

	/* TODO check MS/Sybase format */
	num2 = (DBDECIMAL *) calloc(1, sizeof(DBDECIMAL));
	num2->precision = 20;
	num2->scale = 10;
	dbconvert(dbproc, SYBVARCHAR, (const BYTE *) "246.9", -1, SYBDECIMAL, (BYTE *) num2, sizeof(*num2));

	for (i=0; (ret = dbresults(dbproc)) != NO_MORE_RESULTS; ++i) {
		RETCODE row_code;

		switch (ret) {
		case SUCCEED:
			if (DBROWS(dbproc) == FAIL)
				continue;
			assert(DBROWS(dbproc) == SUCCEED);
			printf("dbrows() returned SUCCEED, processing rows\n");

			memset(num, 0, sizeof(*num));
			num->precision = num2->precision;
			num->scale = num2->scale;
			dbbind(dbproc, 1, bind_type, 0, (BYTE *) num);

			while ((row_code = dbnextrow(dbproc)) != NO_MORE_ROWS) {
				if (row_code == REG_ROW) {
					if (memcmp(num, num2, sizeof(*num)) != 0) {
						fprintf(stderr, "Failed. Output results does not match\n");
						dump_addr(stderr, "numeric: ", num, sizeof(*num));
						dump_addr(stderr, "numeric2:", num2, sizeof(*num2));
						exit(1);
					}
				} else {
					/* not supporting computed rows in this unit test */
					fprintf(stderr, "Failed.  Expected a row\n");
					exit(1);
				}
			}
			break;
		case FAIL:
			fprintf(stderr, "dbresults returned FAIL\n");
			exit(1);
		default:
			fprintf(stderr, "unexpected return code %d from dbresults\n", ret);
			exit(1);
		}
	} /* while dbresults */

	sql_cmd(dbproc);

	free(num2);
	free(num);

	dbclose(dbproc);
}
Exemplo n.º 27
0
int
main(int argc, char **argv)
{
	LOGINREC *login;
	DBPROCESS *dbproc;
	RETPARAM save_param, save_varchar_tds7_param, save_nvarchar_tds7_param;
	
	char teststr[8000+1], abbrev_data[10+3+1], *output;
	char *retname = NULL;
	int i, failed = 0;
	int rettype = 0, retlen = 0, return_status = 0;
	char proc[] = "#t0022";
	char *proc_name = proc;

	int num_resultset = 0, num_empty_resultset = 0;
	int num_params = 6;

	static const char dashes30[] = "------------------------------";
	static const char  *dashes5 = dashes30 + (sizeof(dashes30) - 5), 
			  *dashes20 = dashes30 + (sizeof(dashes30) - 20);

	RETCODE erc, row_code;

	set_malloc_options();
	
	memset(&save_param, 0, sizeof(save_param));
	memset(&save_varchar_tds7_param, 0, sizeof(save_varchar_tds7_param));
	memset(&save_nvarchar_tds7_param, 0, sizeof(save_nvarchar_tds7_param));

	read_login_info(argc, argv);

	printf("Starting %s\n", argv[0]);

	dbinit();

	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	printf("About to logon\n");

	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "rpc");
	dberrhandle(ignore_err_handler);
	DBSETLPACKET(login, -1);
	dberrhandle(syb_err_handler);


	printf("About to open %s.%s\n", SERVER, DATABASE);

	dbproc = dbopen(login, SERVER);
	if (strlen(DATABASE))
		dbuse(dbproc, DATABASE);
	dbloginfree(login);

	printf("Check if server support long identifiers\n");
	sql_cmd(dbproc);
	i = 103;
	dbsetuserdata(dbproc, (BYTE*) &i);
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS)
		while (dbnextrow(dbproc) != NO_MORE_ROWS)
			continue;
	dbsetuserdata(dbproc, NULL);
	if (i == 0) {
		fprintf(stderr, "This server does not support long identifiers\n");
		dbexit();
		return 0;
	}

	dberrhandle(ignore_err_handler);
	dbmsghandle(ignore_msg_handler);

	printf("trying to create a temporary stored procedure\n");
	if (FAIL == init_proc(dbproc, proc_name)) {
		num_params = 4;
		printf("trying to create a permanent stored procedure\n");
		if (FAIL == init_proc(dbproc, ++proc_name))
			exit(EXIT_FAILURE);
	}

	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	printf("Created procedure %s\n", proc_name);

	/* set up and send the rpc */
	printf("executing dbrpcinit\n");
	erc = dbrpcinit(dbproc, proc_name, 0);	/* no options */
	if (erc == FAIL) {
		fprintf(stderr, "Failed line %d: dbrpcinit\n", __LINE__);
		failed = 1;
	}

	for (pb = bindings, i = 0; pb < bindings + sizeof(bindings)/sizeof(bindings[0]); pb++, i++) {
		printf("executing dbrpcparam for %s\n", pb->name);
		if (num_params == 4 && (i == 3 || i == 4))
			continue;
		if ((erc = dbrpcparam(dbproc, pb->name, pb->status, pb->type, pb->maxlen, pb->datalen, pb->value)) == FAIL) {
			fprintf(stderr, "Failed line %d: dbrpcparam\n", __LINE__);
			failed++;
		}

	}
	printf("executing dbrpcsend\n");
	param_data5 = 0x11223344;
	erc = dbrpcsend(dbproc);
	if (erc == FAIL) {
		fprintf(stderr, "Failed line %d: dbrpcsend\n", __LINE__);
		exit(1);
	}

	/* wait for it to execute */
	printf("executing dbsqlok\n");
	erc = dbsqlok(dbproc);
	if (erc == FAIL) {
		fprintf(stderr, "Failed line %d: dbsqlok\n", __LINE__);
		exit(1);
	}

	/* retrieve outputs per usual */
	printf("fetching results\n");
	while ((erc = dbresults(dbproc)) != NO_MORE_RESULTS) {
		printf("fetched resultset %d %s:\n", 1+num_resultset, erc==SUCCEED? "successfully":"unsuccessfully");
		if (erc == SUCCEED) { 
			const int ncol = dbnumcols(dbproc);
			int empty_resultset = 1, c;
			enum {buflen=1024, nbuf=5};
			char bound_buffers[nbuf][buflen] = { "one", "two", "three", "four", "five" };

			++num_resultset;
			
			for( c=0; c < ncol && c < nbuf; c++ ) {
				printf("column %d (%s) is %d wide, ", c+1, dbcolname(dbproc, c+1), colwidth(dbproc, c+1));
				printf("buffer initialized to '%s'\n", bound_buffers[c]);
			}
			for( c=0; c < ncol && c < nbuf; c++ ) {
				erc = dbbind(dbproc, c+1, STRINGBIND, 0, (BYTE *) bound_buffers[c]);
				if (erc == FAIL) {
					fprintf(stderr, "Failed line %d: dbbind\n", __LINE__);
					exit(1);
				}

				printf("%-*s ", colwidth(dbproc, c+1), dbcolname(dbproc, c+1));
			}
			printf("\n");

			while ((row_code = dbnextrow(dbproc)) != NO_MORE_ROWS) {
				empty_resultset = 0;
				if (row_code == REG_ROW) {
					int c;
					for( c=0; c < ncol && c < nbuf; c++ ) {
						printf("%-*s ", colwidth(dbproc, c+1), bound_buffers[c]);
					}
					printf("\n");
				} else {
					/* not supporting computed rows in this unit test */
					failed = 1;
					fprintf(stderr, "Failed.  Expected a row\n");
					exit(1);
				}
			}
			printf("row count %d\n", (int) dbcount(dbproc));
			printf("hasretstatus %d\n", dbhasretstat(dbproc));
			if (num_resultset == 4 && !dbhasretstat(dbproc)) {
				fprintf(stderr, "dbnextrow should have set hasretstatus after last recordset\n");
				exit(1);
			}
			if (empty_resultset)
				++num_empty_resultset;
		} else {
			fprintf(stderr, "Expected a result set.\n");
			exit(1);
		}
	} /* while dbresults */
	
	/* check return status */
	printf("retrieving return status...\n");
	if (dbhasretstat(dbproc) == TRUE) {
		printf("%d\n", return_status = dbretstatus(dbproc));
	} else {
		printf("none\n");
	}

	/* 
	 * Check output parameter values 
	 */
	if (dbnumrets(dbproc) != num_params) {	/* dbnumrets missed something */
		fprintf(stderr, "Expected %d output parameters.\n", num_params);
		exit(1);
	}
	printf("retrieving output parameters...\n");
	printf("%-5s %-20s %5s %6s  %-30s\n", "param", "name", "type", "length", "data");
	printf("%-5s %-20s %5s %5s- %-30s\n", dashes5, dashes20, dashes5, dashes5, dashes30);
	for (i = 1; i <= dbnumrets(dbproc); i++) {
		retname = dbretname(dbproc, i);
		rettype = dbrettype(dbproc, i);
		retlen = dbretlen(dbproc, i);
		dbconvert(dbproc, rettype, dbretdata(dbproc, i), retlen, SYBVARCHAR, (BYTE*) teststr, -1);
		if(retlen <= 10) {
			output = teststr;
		} else {
			memcpy(abbrev_data, teststr, 10);
			sprintf(&abbrev_data[10], "...");
			output = abbrev_data;
		}
		printf("%-5d %-20s %5d %6d  %-30s\n", i, retname, rettype, retlen, output);

		save_retparam(&save_param, retname, teststr, rettype, retlen);
		if (i == 4) {
			save_retparam(&save_varchar_tds7_param, retname, teststr, rettype, retlen);
		}
		if (i == 5) {
			save_retparam(&save_nvarchar_tds7_param, retname, teststr, rettype, retlen);
		}
	}

	/* 
	 * Test the last parameter for expected outcome 
	 */
	if ((save_param.name == NULL) || strcmp(save_param.name, bindings[5].name)) {
		fprintf(stderr, "Expected retname to be '%s', got ", bindings[5].name);
		if (save_param.name == NULL) 
			fprintf(stderr, "<NULL> instead.\n");
		else
			fprintf(stderr, "'%s' instead.\n", save_param.name);
		exit(1);
	}
	if (strcmp(save_param.value, "3")) {
		fprintf(stderr, "Expected retdata to be 3.\n");
		exit(1);
	}
	if (save_param.type != SYBINT4) {
		fprintf(stderr, "Expected rettype to be SYBINT4 was %d.\n", save_param.type);
		exit(1);
	}
	if (save_param.len != 4) {
		fprintf(stderr, "Expected retlen to be 4.\n");
		exit(1);
	}

	if (num_params == 6) {
		/*
		 * Test name, size, contents of the VARCHAR(8000) output parameter
		 */
		if ((save_varchar_tds7_param.name == NULL) || strcmp(save_varchar_tds7_param.name, bindings[3].name)) {
			fprintf(stderr, "Expected retname to be '%s', got ", bindings[3].name);
			if (save_varchar_tds7_param.name == NULL)
				fprintf(stderr, "<NULL> instead.\n");
			else
				fprintf(stderr, "'%s' instead.\n", save_varchar_tds7_param.name);
			exit(1);
		}
		if (save_varchar_tds7_param.type != SYBVARCHAR) {
			fprintf(stderr, "Expected rettype to be SYBVARCHAR was %d.\n", save_varchar_tds7_param.type);
			exit(1);
		}
		if (save_varchar_tds7_param.len != 8000) {
			fprintf(stderr, "Expected retlen to be 8000 was %d.\n", save_varchar_tds7_param.len);
			exit(1);
		}

		/*
		 * Test name, size, contents of the NVARCHAR(4000) output parameter
		 */
		if ((save_nvarchar_tds7_param.name == NULL) || strcmp(save_nvarchar_tds7_param.name, bindings[4].name)) {
			fprintf(stderr, "Expected retname to be '%s', got ", bindings[4].name);
			if (save_varchar_tds7_param.name == NULL)
				fprintf(stderr, "<NULL> instead.\n");
			else
				fprintf(stderr, "'%s' instead.\n", save_nvarchar_tds7_param.name);
			exit(1);
		}
		if (save_nvarchar_tds7_param.len != 4000) {
			fprintf(stderr, "Expected retlen to be 4000 was %d.\n", save_nvarchar_tds7_param.len);
			exit(1);
		}
	}

	if(42 != return_status) {
		fprintf(stderr, "Expected status to be 42.\n");
		exit(1);
	}

	printf("Good: Got 6 output parameters and 1 return status of %d.\n", return_status);


	/* Test number of result sets */
	if (num_resultset != 4) {
		fprintf(stderr, "Expected 4 resultset got %d.\n", num_resultset);
		exit(1);
	}
	if (num_empty_resultset != 1) {
		fprintf(stderr, "Expected an empty resultset got %d.\n", num_empty_resultset);
		exit(1);
	}
	printf("Good: Got %d resultsets and %d empty resultset.\n", num_resultset, num_empty_resultset);



	printf("Dropping procedure\n");
	sql_cmd(dbproc);
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}
	dbexit();

	printf("%s %s\n", __FILE__, (failed ? "failed!" : "OK"));

	free_retparam(&save_param);
	free_retparam(&save_varchar_tds7_param);
	free_retparam(&save_nvarchar_tds7_param);

	return failed ? 1 : 0;
}
Exemplo n.º 28
0
int
main(int argc, char **argv)
{
	LOGINREC *login;
	DBPROCESS *dbproc;
	int i;
	DBINT erc;

	RETCODE results_retcode;
	int rowcount;
	int colcount;
	int row_retcode;

	set_malloc_options();

	read_login_info(argc, argv);
	if (argc > 1) {
		argc -= optind;
		argv += optind;
	}

	printf("Starting %s\n", argv[0]);

	/* Fortify_EnterScope(); */
	dbinit();

	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	printf("About to logon as \"%s\"\n", USER);

	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "wf_dbresults");

	if (argc > 1) {
		printf("server and login timeout overrides (%s and %s) detected\n", argv[0], argv[1]);
		strcpy(SERVER, argv[0]);
		i = atoi(argv[1]);
		if (i) {
			i = dbsetlogintime(i);
			printf("dbsetlogintime returned %s.\n", (i == SUCCEED) ? "SUCCEED" : "FAIL");
		}
	}

	printf("About to open \"%s\"\n", SERVER);

	dbproc = dbopen(login, SERVER);
	if (!dbproc) {
		fprintf(stderr, "Unable to connect to %s\n", SERVER);
		return 1;
	}
	dbloginfree(login);

	printf("Using database \"%s\"\n", DATABASE);
	if (strlen(DATABASE)) {
		erc = dbuse(dbproc, DATABASE);
		assert(erc == SUCCEED);
	}

	sql_cmd(dbproc);
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}

	/*
	 * This test is written to simulate how dblib is used in PDO
	 * functions are called in the same order they would be if doing
	 * PDO::query followed by some number of PDO::statement->nextRowset
	 */

	/*
	 * First, call everything that happens in PDO::query
	 * this will return the results of the CREATE TABLE statement
	 */
	dbcancel(dbproc);

	printf("using sql_cmd\n");
	sql_cmd(dbproc);
	dbsqlexec(dbproc);

	results_retcode = dbresults(dbproc);
	rowcount = DBCOUNT(dbproc);
	colcount = dbnumcols(dbproc);

	printf("** CREATE TABLE **\n");
	printf("RETCODE: %d\n", results_retcode);
	printf("ROWCOUNT: %d\n", rowcount);
	printf("COLCOUNT: %d\n\n", colcount);

	/* check that the results correspond to the create table statement */
	assert(results_retcode == SUCCEED);
	assert(rowcount == -1);
	assert(colcount == 0);

	/* now simulate calling nextRowset() for each remaining statement in our batch */

	/*
	 * INSERT
	 */
	printf("** INSERT **\n");

	/* there shouldn't be any rows in this resultset yet, it's still from the CREATE TABLE */
	row_retcode = dbnextrow(dbproc);
	printf("dbnextrow retcode: %d\n", results_retcode);
	assert(row_retcode == NO_MORE_ROWS);

	results_retcode = dbresults(dbproc);
	rowcount = DBCOUNT(dbproc);
	colcount = dbnumcols(dbproc);

	printf("RETCODE: %d\n", results_retcode);
	printf("ROWCOUNT: %d\n", rowcount);
	printf("COLCOUNT: %d\n\n", colcount);

	assert(results_retcode == SUCCEED);
	assert(rowcount == 3);
	assert(colcount == 0);

	/*
	 * SELECT
	 */
	printf("** SELECT **\n");

	/* the rowset is still from the INSERT and should have no rows */
	row_retcode = dbnextrow(dbproc);
	printf("dbnextrow retcode: %d\n", results_retcode);
	assert(row_retcode == NO_MORE_ROWS);

	results_retcode = dbresults(dbproc);
	rowcount = DBCOUNT(dbproc);
	colcount = dbnumcols(dbproc);

	printf("RETCODE: %d\n", results_retcode);
	printf("ROWCOUNT: %d\n", rowcount);
	printf("COLCOUNT: %d\n\n", colcount);

	assert(results_retcode == SUCCEED);
	assert(rowcount == -1);
	assert(colcount == 1);

	/* now we expect to find three rows in the rowset */
	row_retcode = dbnextrow(dbproc);
	printf("dbnextrow retcode: %d\n", row_retcode);
	assert(row_retcode == REG_ROW);
	row_retcode = dbnextrow(dbproc);
	printf("dbnextrow retcode: %d\n", row_retcode);
	assert(row_retcode == REG_ROW);
	row_retcode = dbnextrow(dbproc);
	printf("dbnextrow retcode: %d\n\n", row_retcode);
	assert(row_retcode == REG_ROW);

	/*
	 * UPDATE
	 */
	printf("** UPDATE **\n");

	/* check that there are no rows left, then we'll get the results from the UPDATE */
	row_retcode = dbnextrow(dbproc);
	printf("dbnextrow retcode: %d\n", row_retcode);
	assert(row_retcode == NO_MORE_ROWS);

	results_retcode = dbresults(dbproc);
	rowcount = DBCOUNT(dbproc);
	colcount = dbnumcols(dbproc);

	printf("RETCODE: %d\n", results_retcode);
	printf("ROWCOUNT: %d\n", rowcount);
	printf("COLCOUNT: %d\n\n", colcount);

	assert(results_retcode == SUCCEED);
	assert(rowcount == 3);
	/*assert(colcount == 0); TODO: why does an update get a column? */

	/*
	 * SELECT
	 */
	printf("** SELECT **\n");

	row_retcode = dbnextrow(dbproc);
	printf("dbnextrow retcode: %d\n", row_retcode);
	assert(row_retcode == NO_MORE_ROWS);

	results_retcode = dbresults(dbproc);
	rowcount = DBCOUNT(dbproc);
	colcount = dbnumcols(dbproc);

	printf("RETCODE: %d\n", results_retcode);
	printf("ROWCOUNT: %d\n", rowcount);
	printf("COLCOUNT: %d\n\n", colcount);

	assert(results_retcode == SUCCEED);
	assert(rowcount == -1);
	assert(colcount == 1);

	/* now we expect to find three rows in the rowset again */
	row_retcode = dbnextrow(dbproc);
	printf("dbnextrow retcode: %d\n", row_retcode);
	assert(row_retcode == REG_ROW);
	row_retcode = dbnextrow(dbproc);
	printf("dbnextrow retcode: %d\n", row_retcode);
	assert(row_retcode == REG_ROW);
	row_retcode = dbnextrow(dbproc);
	printf("dbnextrow retcode: %d\n\n", row_retcode);
	assert(row_retcode == REG_ROW);

	/*
	 * DROP
	 */
	printf("** DROP **\n");

	row_retcode = dbnextrow(dbproc);
	printf("dbnextrow retcode: %d\n", row_retcode);
	assert(row_retcode == NO_MORE_ROWS);

	results_retcode = dbresults(dbproc);
	rowcount = DBCOUNT(dbproc);
	colcount = dbnumcols(dbproc);

	printf("RETCODE: %d\n", results_retcode);
	printf("ROWCOUNT: %d\n", rowcount);
	printf("COLCOUNT: %d\n\n", colcount);

	assert(results_retcode == SUCCEED);
	assert(rowcount == -1);
	/* assert(colcount == 0); */

	/* Call one more time to be sure we get NO_MORE_RESULTS */
	row_retcode = dbnextrow(dbproc);
	printf("dbnextrow retcode: %d\n", row_retcode);
	assert(row_retcode == NO_MORE_ROWS);

	results_retcode = dbresults(dbproc);
	rowcount = DBCOUNT(dbproc);
	colcount = dbnumcols(dbproc);

	printf("RETCODE: %d\n", results_retcode);
	printf("ROWCOUNT: %d\n", rowcount);
	printf("COLCOUNT: %d\n\n", colcount);

	assert(results_retcode == NO_MORE_RESULTS);
	assert(rowcount == -1);
	/* assert(colcount == 0); */

	dbexit();

	printf("%s OK\n", __FILE__);
	return 0;
}
Exemplo n.º 29
0
static int
test(int argc, char **argv, int over4k)
{
	const int rows_to_add = 3;
	LOGINREC *login;
	DBPROCESS *dbproc;
	DBPROCESS *blobproc;
	int i;
	DBINT testint;
	FILE *fp;
	long result, isiz;
	char *blob, *rblob;
	unsigned char *textPtr, *timeStamp;
	char objname[256];
	char sqlCmd[256];
	char rbuf[BLOB_BLOCK_SIZE];
	long numread;
	int numtowrite, numwritten;

	set_malloc_options();

	read_login_info(argc, argv);
	fprintf(stdout, "Starting %s\n", argv[0]);
	dbinit();

	dberrhandle(syb_err_handler);
	dbmsghandle(syb_msg_handler);

	fprintf(stdout, "About to logon\n");

	login = dblogin();
	DBSETLPWD(login, PASSWORD);
	DBSETLUSER(login, USER);
	DBSETLAPP(login, "t0014");

	fprintf(stdout, "About to open %s..%s for user '%s'\n", SERVER, DATABASE, USER);

	dbproc = dbopen(login, SERVER);
	blobproc = dbopen(login, SERVER);
	if (strlen(DATABASE)) {
		dbuse(dbproc, DATABASE);
		dbuse(blobproc, DATABASE);
	}
	dbloginfree(login);
	fprintf(stdout, "After logon\n");

	fprintf(stdout, "About to read binary input file\n");

	if (argc == 1) {
		argv = testargs;
		argc = 3;
	}
	if (argc < 3) {
		fprintf(stderr, "Usage: %s infile outfile\n", argv[0]);
		return 1;
	}

	if ((fp = fopen(argv[1], "rb")) == NULL) {
		fprintf(stderr, "Cannot open input file: %s\n", argv[1]);
		return 2;
	}
	result = fseek(fp, 0, SEEK_END);
	isiz = ftell(fp);
	result = fseek(fp, 0, SEEK_SET);

	blob = (char *) malloc(isiz);
	result = fread((void *) blob, isiz, 1, fp);
	assert(result == 1);
	fclose(fp);

	/* FIXME this test seem to not work using temporary tables (sybase?)... */
	fprintf(stdout, "Dropping table\n");
	sql_cmd(dbproc);
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}

	fprintf(stdout, "creating table\n");
	sql_cmd(dbproc);
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}


	fprintf(stdout, "insert\n");
	for (i = 0; i < rows_to_add; i++) {
		sql_cmd(dbproc);
		dbsqlexec(dbproc);
		while (dbresults(dbproc) != NO_MORE_RESULTS) {
			/* nop */
		}
	}

	for (i = 0; i < rows_to_add; i++) {
		sql_cmd(dbproc);
		dbsqlexec(dbproc);
		if (dbresults(dbproc) != SUCCEED) {
			fprintf(stderr, "Error inserting blob\n");
			return 4;
		}

		while ((result = dbnextrow(dbproc)) != NO_MORE_ROWS) {
			result = REG_ROW;
			result = DBTXPLEN;
			strcpy(objname, "dblib0014.PigTure");
			textPtr = dbtxptr(dbproc, 1);
			timeStamp = dbtxtimestamp(dbproc, 1);

			if (!textPtr && !timeStamp && dbtds(dbproc) >= DBTDS_7_2) {
				printf("Protocol 7.2+ detected, test not supported\n");
				free(blob);
				dbexit();
				exit(0);
			}

			/*
			 * Use #ifdef if you want to test dbmoretext mode (needed for 16-bit apps)
			 * Use #ifndef for big buffer version (32-bit)
			 */
			if (over4k) {
				if (dbwritetext(blobproc, objname, textPtr, DBTXPLEN, timeStamp, TRUE, isiz, (BYTE*) blob) != SUCCEED)
					return 5;
			} else {
				if (dbwritetext(blobproc, objname, textPtr, DBTXPLEN, timeStamp, TRUE, isiz, NULL) != SUCCEED)
					return 15;
				dbsqlok(blobproc);
				dbresults(blobproc);

				numtowrite = 0;
				/* Send the update value in chunks. */
				for (numwritten = 0; numwritten < isiz; numwritten += numtowrite) {
					numtowrite = (isiz - numwritten);
					if (numtowrite > BLOB_BLOCK_SIZE)
						numtowrite = BLOB_BLOCK_SIZE;
					dbmoretext(blobproc, (DBINT) numtowrite, (BYTE *) (blob + numwritten));
				}
				dbsqlok(blobproc);
				while (dbresults(blobproc) != NO_MORE_RESULTS);
			}
		}
	}

	fprintf(stdout, "select\n");

	sql_cmd(dbproc);
	dbsqlexec(dbproc);

	if (dbresults(dbproc) != SUCCEED) {
		fprintf(stdout, "Was expecting a result set.");
		exit(1);
	}

	for (i = 1; i <= dbnumcols(dbproc); i++) {
		printf("col %d is %s\n", i, dbcolname(dbproc, i));
	}

	if (SUCCEED != dbbind(dbproc, 1, INTBIND, -1, (BYTE *) & testint)) {
		fprintf(stderr, "Had problem with bind\n");
		abort();
	}

	for (i = 0; i < rows_to_add; i++) {
	char expected[1024];

		sprintf(expected, "row %03d", i);

		if (REG_ROW != dbnextrow(dbproc)) {
			fprintf(stderr, "Failed.  Expected a row\n");
			exit(1);
		}
		if (testint != i) {
			fprintf(stderr, "Failed.  Expected i to be %d, was %d\n", i, (int) testint);
			abort();
		}

		/* get the image */
		strcpy(sqlCmd, "SET TEXTSIZE 2147483647");
		dbcmd(blobproc, sqlCmd);
		dbsqlexec(blobproc);

		if (dbresults(blobproc) != SUCCEED) {
			dbcancel(blobproc);
			return 16;
		}

		sprintf(sqlCmd, "SELECT PigTure FROM dblib0014 WHERE i = %d", i);
		dbcmd(blobproc, sqlCmd);
		dbsqlexec(blobproc);
		if (dbresults(blobproc) != SUCCEED) {
			fprintf(stderr, "Error extracting blob\n");
			return 6;
		}

		numread = 0;
		rblob = NULL;
		while ((result = dbreadtext(blobproc, rbuf, BLOB_BLOCK_SIZE)) != NO_MORE_ROWS) {
			if (result != 0) {	/* this indicates not end of row */
				rblob = (char*) realloc(rblob, result + numread);
				memcpy((void *) (rblob + numread), (void *) rbuf, result);
				numread += result;
			}
		}

		if (i == 0) {
			printf("Saving first blob data row to file: %s\n", argv[2]);
			if ((fp = fopen(argv[2], "wb")) == NULL) {
				fprintf(stderr, "Unable to open output file: %s\n", argv[2]);
				return 3;
			}

			result = fwrite((void *) rblob, numread, 1, fp);
			fclose(fp);
		}

		printf("Read blob data row %d --> %s %ld byte comparison\n",
		       (int) testint, (memcmp(blob, rblob, numread)) ? "failed" : "PASSED", numread);
		free(rblob);
	}

	if (dbnextrow(dbproc) != NO_MORE_ROWS) {
		fprintf(stderr, "Was expecting no more rows\n");
		exit(1);
	}

	free(blob);

	fprintf(stdout, "Dropping table\n");
	sql_cmd(dbproc);
	dbsqlexec(dbproc);
	while (dbresults(dbproc) != NO_MORE_RESULTS) {
		/* nop */
	}

	dbexit();

	return 0;
}
Exemplo n.º 30
0
LOGINREC *
get_login(int argc, char *argv[], OPTIONS *options)
{
	LOGINREC *login;
	int ch;

	extern char *optarg;
	extern int optind;

	assert(options && argv);
	
	options->appname = basename(argv[0]);
	
	login = dblogin();
	
	if (!login) {
		fprintf(stderr, "%s: unable to allocate login structure\n", options->appname);
		exit(1);
	}
	
	DBSETLAPP(login, options->appname);
	
	if (-1 == gethostname(options->hostname, sizeof(options->hostname))) {
		perror("unable to get hostname");
	} else {
		DBSETLHOST(login, options->hostname);
	}

	while ((ch = getopt(argc, argv, "U:P:S:D:i:o:e:v")) != -1) {
		switch (ch) {
		case 'U':
			DBSETLUSER(login, optarg);
			break;
		case 'P':
			DBSETLPWD(login, optarg);
			break;
		case 'S':
			options->servername = strdup(optarg);
			break;
		case 'D':
			options->database = strdup(optarg);
			break;
		case 'i':
			options->input_filename = strdup(optarg);
			break;
		case 'o':
			options->output_filename = strdup(optarg);
			break;
		case 'e':
			options->error_filename = strdup(optarg);
			break;
		case 'v':
			options->fverbose = 1;
			break;
		case '?':
		default:
			usage(options->appname);
			exit(1);
		}
	}
	
	if (!options->servername) {
		usage(options->appname);
		exit(1);
	}
	
	return login;
}