Esempio n. 1
0
/**
 * Creates a new registry object. To start using a registry, one must first be
 * attached with `reg_attach`.
 *
 * @param [out] regPtr address of the allocated registry
 * @param [out] errPtr on error, a description of the error that occurred
 * @return             true if success; false if failure
 */
int reg_open(reg_registry** regPtr, reg_error* errPtr) {
    reg_registry* reg = malloc(sizeof(reg_registry));
    if (!reg) {
        return 0;
    }
    if (sqlite3_open(NULL, &reg->db) == SQLITE_OK) {
        /* Enable extended result codes, requires SQLite >= 3.3.8
         * Check added for compatibility with Tiger. */
#if SQLITE_VERSION_NUMBER >= 3003008
        sqlite3_extended_result_codes(reg->db, 1);
#endif

        sqlite3_busy_timeout(reg->db, 25);

        if (init_db(reg->db, errPtr)) {
            reg->status = reg_none;
            *regPtr = reg;
            return 1;
        }
    } else {
        reg_sqlite_error(reg->db, errPtr, NULL);
    }
    sqlite3_close(reg->db);
    free(reg);
    return 0;
}
Esempio n. 2
0
void
query_db(char *query)
{
	sqlite3 *db;
	sqlite3_stmt *stmt;
	int rc = 0;
	char *sql = NULL;

	db = init_db();	
	sql = sqlite3_mprintf("SELECT snippet(fts) FROM fts WHERE fts MATCH %Q AND "
			"i = 0 LIMIT 10", query);
	if (sql == NULL) {
		sqlite3_close(db);
		errx(EXIT_FAILURE, "sqlite3_mprintf failed");
	}
	
	rc = sqlite3_prepare_v2(db, sql, -1, &stmt, NULL);
	if (rc != SQLITE_OK) {
		warnx("sqlite3_prepare failed while searching");
		warnx("%S", sqlite3_errmsg(db));
		sqlite3_close(db);
		sqlite3_free(sql);
		exit(EXIT_FAILURE);
	}
	
	sqlite3_free(sql);
	
	while (sqlite3_step(stmt) == SQLITE_ROW) {
		printf("%s\n", sqlite3_column_text(stmt, 0));
	}
	
	sqlite3_finalize(stmt);
	sqlite3_close(db);
}
Esempio n. 3
0
/**
 * Runs VACUUM (compact/defragment) on the given db file.
 * Works on a path rather than an open db pointer because you can't vacuum an
 * attached db, which is what the rest of the registry uses for some reason.
 *
 * @param [in] db_path path to db file to vacuum
 * @return             true if success; false if failure
 */
int reg_vacuum(char *db_path) {
    sqlite3* db;
    sqlite3_stmt* stmt = NULL;
    int result = 0;
    reg_error err;

    if (sqlite3_open(db_path, &db) == SQLITE_OK) {
        if (!init_db(db, &err)) {
            sqlite3_close(db);
            return 0;
        }
    } else {
        return 0;
    }

    if (sqlite3_prepare_v2(db, "VACUUM", -1, &stmt, NULL) == SQLITE_OK) {
        int r;
        /* XXX: Busy waiting, consider using sqlite3_busy_handler/timeout */
        do {
            sqlite3_step(stmt);
            r = sqlite3_reset(stmt);
            if (r == SQLITE_OK) {
                result = 1;
            }
        } while (r == SQLITE_BUSY);
    }
    if (stmt) {
        sqlite3_finalize(stmt);
    }
    sqlite3_close(db);
    return result;
}
Esempio n. 4
0
/*
 * get a person from the database
 *
 * returns phone# or -1 if not found
 */
long get_number(char* name) {
    int dbfile = init_db();
    int record_count = 0;
    PhoneRecord phone_record;
    
    // see, how many entries the db has ...
    lseek(dbfile, 0, SEEK_SET);
    read(dbfile, &record_count, sizeof (int));
    if (record_count == 0) {
        return -1;
    }
    
    // set the pointer to the last entry
    set_to_record(dbfile, record_count);
    // run through all entries towards the beginning, if you find an entry that matches the name, bail out
    while (record_count--) {
        read(dbfile, &phone_record, sizeof (PhoneRecord));
        set_to_record(dbfile, record_count);
        
        if (!strcmp(phone_record.name, name)) {
            return phone_record.phone_number;
        }
    }
    return -1;
}
Esempio n. 5
0
int main()
{
    database_init(3);
    init_db();

    printf("Welcome to eCommerce v0.1\n");

    while (1)
    {
        char choice = menu();
        if (choice == 0)
            break;
        else if (choice == 'a')
            list();
        else if (choice == 'b')
            buy();
        else if (choice == 'c')
            sell();
        else
            printf("Invalid selection\n");
    }

    database_close();
    return 0;
}
Esempio n. 6
0
int main(int argc, char *argv[])
{
    int i, r;

    i = proc_args(argc, argv);

    if (!args.subcmd)
        do_usage();

    if (args.dbfile)
    {
        if (args.needwrite)
        {
            fprintf(stderr, "you can't write to a database specified with -d.\n");
            return 1;
        }
        else
            r = init_named_db(args.dbfile);
    }
    else
        r = init_db(args.needwrite);

    if (r)
    {
        fprintf(stderr, "can't open database.\n");
        return 1;
    }

    i++; /* eat argv[0] */
    i = args.subcmd(argc - i, argv + i);

    close_db();

    return i;
}
int main(int argc, char *argv[])
{
    int ret;
    ret = init_db();
    if (ret != 0){
        logger("Error with DB; terminating.");
        exit(1);
    }
 
    DB *dbp = getDBP(); 
    init_data(dbp); //agrego valores a la base de datos   
    
    pthread_t v_thread_menu_servidor;
    pthread_create (&v_thread_menu_servidor, NULL, menu_servidor, NULL);

    if (start_tcp_server())
    {
        logger("Server started successfully");
    }
    else
    {
        stop_main();
        return EXIT_FAILURE;
    }

    listen_and_accept_new_clients();

    stop_main();
    cerrarLogger();
    dbp->close(dbp, 0);
    return EXIT_SUCCESS;
}
Esempio n. 8
0
static void
erl_init(int ncpu)
{
    init_benchmarking();

#ifdef ERTS_SMP
    erts_system_block_init();
#endif

    erts_init_monitors();
    erts_init_gc();
    erts_init_time();
    erts_init_sys_common_misc();
    erts_init_process(ncpu);
    erts_init_scheduling(use_multi_run_queue,
			 no_schedulers,
			 no_schedulers_online);
    erts_init_cpu_topology(); /* Must be after init_scheduling */
    H_MIN_SIZE      = erts_next_heap_size(H_MIN_SIZE, 0);
    BIN_VH_MIN_SIZE = erts_next_heap_size(BIN_VH_MIN_SIZE, 0);

    erts_init_trace();
    erts_init_binary();
    erts_init_bits();
    erts_init_fun_table();
    init_atom_table();
    init_export_table();
    init_module_table();
    init_register_table();
    init_message();
    erts_bif_info_init();
    erts_ddll_init();
    init_emulator();
    erts_bp_init();
    init_db(); /* Must be after init_emulator */
    erts_bif_timer_init();
    erts_init_node_tables();
    init_dist();
    erl_drv_thr_init();
    init_io();
    init_copy();
    init_load();
    erts_init_bif();
    erts_init_bif_chksum();
    erts_init_bif_binary();
    erts_init_bif_re();
    erts_init_unicode(); /* after RE to get access to PCRE unicode */
    erts_delay_trap = erts_export_put(am_erlang, am_delay_trap, 2);
    erts_late_init_process();
#if HAVE_ERTS_MSEG
    erts_mseg_late_init(); /* Must be after timer (erts_init_time()) and thread
			      initializations */
#endif
#ifdef HIPE
    hipe_mode_switch_init(); /* Must be after init_load/beam_catches/init */
#endif
    packet_parser_init();
    erl_nif_init();
}
Esempio n. 9
0
int main(void)
{
	int len;
	char *lenstr,poststr[512];
	char *player_id, *server_id;
	int can_share = 1;

	init_db((char *)"127.0.0.1", 3306, (char *)"pay", (char *)"root", (char *)"123456");

	printf("Content-Type:text/html\n\n");
	lenstr=getenv("CONTENT_LENGTH");
	if(lenstr == NULL) {
		printf("<DIV STYLE=\"COLOR:RED\">Errorarameters should be entered!</DIV>\n");
		return (0);
	}
	len=atoi(lenstr) + 1;
	if (len >= 512)
		return (0);
	
	fgets(poststr,len,stdin);
	parse_post_data(poststr, len);
	server_id = get_value((char *)"server_id");
	player_id = get_value((char *)"player_id");
	if (!server_id || !player_id)
		return (0);	
	
	MYSQL_RES *res = NULL;
	MYSQL_ROW row;	
	char sql[256];

	sprintf(sql, "select last_share_time, share_times, pay_times from share where server_id = %s and player_id = %s", server_id, player_id);
	res = query(sql, 1, NULL);
	if (!res) {
		send_no_record();
		goto done;
	}
	row = fetch_row(res);
	if (!row) {
		send_no_record();
		goto done;
	}


	if (!check_can_share(row)) {
		can_share = 0;
	}

	printf("[%d, %s, %s]", can_share, row[1], row[2]);
	
done:
	if (res)
		free_query(res);
	fflush(stdout);
	close_db();		
	return 0;
}
Esempio n. 10
0
int main(int argc, char *argv[])
{
  if (argc != 2) {
    exit(1);
  }
  char db_name[32] = "cstore";
  char *table_name = argv[1];
  char full_table_name[32];
  if (!init_db()) {
    exit(1);
  }
  if (!create_db(db_name)) {
    std::cerr << "create_db failed" << std::endl;
    exit(1);
  }

  sprintf(full_table_name, "%s/%s", db_name, table_name);
  if (!create_schema(full_table_name)) {
    std::cerr << "create_schema failed" << std::endl;
    exit(1);
  }

  ib_crsr_t ib_crsr;

  std::string line;
  int i = 0;
  ib_trx_t ib_trx = ib_trx_begin(IB_TRX_REPEATABLE_READ);
  ib_cursor_open_table(full_table_name, ib_trx, &ib_crsr);
  while (getline(std::cin, line)) {
    std::vector<std::string> strs;
    boost::split(strs, line, boost::is_any_of(" ") );
    ib_tpl_t tpl = ib_clust_read_tuple_create(ib_crsr);
    ib_tuple_write_u32(tpl, 0, atoi(strs[0].c_str()));
    ib_tuple_write_u32(tpl, 1, atoi(strs[1].c_str()));
    ib_tuple_write_u32(tpl, 2, atoi(strs[2].c_str()));
    ib_err_t err = ib_cursor_insert_row(ib_crsr, tpl);
    if (err != DB_SUCCESS) {
      std::cerr << "insert_row failed" << std::endl;
    }
    ib_tuple_delete(tpl);
    if (++i % 10000 == 0) {
      std::cout << i << std::endl;
      ib_cursor_close(ib_crsr); 
      ib_trx_commit(ib_trx);
      ib_trx = ib_trx_begin(IB_TRX_REPEATABLE_READ);
      ib_cursor_open_table(full_table_name, ib_trx, &ib_crsr);
    }
  }
  ib_cursor_close(ib_crsr); 
  ib_trx_commit(ib_trx);
  fin_db();

  return 0;
}
Esempio n. 11
0
File: api.c Progetto: CESNET/torque
int init_rep() {
    pthread_t cnt_thr, lt_thr, i_thr, elect_thr;
    int nsites, ret;
    struct node_struct *nd;

    nd = &node;
    if (!initialized) {
        initialized = 1;
        init_db(&node);
        paxos_state_print();
        if (process_logs(&node) != 0) {
            if ((ret = pthread_mutex_lock(&nd->mtmutex)) != 0) {
                pax_log(LOG_ERR, "can't lock mutex\n");
                exit(EX_OSERR);
            }
            nd->updating = BFALSE;
            nd->non_voting = BTRUE; /*The node can vote again*/

            if ((ret = pthread_mutex_unlock(&nd->mtmutex)) != 0) {
                pax_log(LOG_ERR, "can't unlock mutex\n");
                exit(EX_OSERR);
            }

        }
        nsites = node.number_of_nodes;
        clear_dumps();

        if ((ret = pthread_create(&lt_thr, NULL, listen_thread, NULL)) != 0) {
            pax_log(LOG_ERR, "can't create connect thread: %s\n", strerror(errno));
            goto err;
        }


        if ((ret = pthread_create(&cnt_thr, NULL, contact_group, NULL)) != 0) {
            pax_log(LOG_ERR, "can't create connect-all thread: %s\n", strerror(errno));
            goto err;
        }

        if ((ret = pthread_create(&i_thr, NULL, dist_metric_int, NULL)) != 0) {
            pax_log(LOG_ERR, "can't create dist_metric_int thread: %s\n", strerror(errno));
            goto err;
        }
        sleep(1); /*Wait for others to be started*/
        if ((ret = pthread_create(&elect_thr, NULL, election_thread, NULL)) != 0) {
            pax_log(LOG_ERR, "can't create election-thread: %s\n", strerror(errno));
            goto err;
        }
        return 0;
err:
        return ret;
    }
    return 0;
}
Esempio n. 12
0
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

    connect(ui->actionNewEntry, SIGNAL(triggered()), this, SLOT(newEntry()));
    connect(ui->actionChange_Password, SIGNAL(triggered()),this, SLOT(changePassword()));

    connect(ui->tableView,SIGNAL(clicked(QModelIndex)),this,SLOT(tableViewClicked(QModelIndex)));

    db = init_db();
}
Esempio n. 13
0
EXPORT int MM_aliasdb(int action, Imodman *mm_, Arena *arena)
{
	if (action == MM_LOAD)
	{
		mm = mm_;
		pd = mm->GetInterface(I_PLAYERDATA, ALLARENAS);
		lm = mm->GetInterface(I_LOGMAN, ALLARENAS);
		cfg = mm->GetInterface(I_CONFIG, ALLARENAS);
		cmd = mm->GetInterface(I_CMDMAN, ALLARENAS);
		chat = mm->GetInterface(I_CHAT, ALLARENAS);
		net = mm->GetInterface(I_NET, ALLARENAS);
		chatnet = mm->GetInterface(I_CHATNET, ALLARENAS);
		db = mm->GetInterface(I_RELDB, ALLARENAS);

		if (!pd || !cfg || !cmd || !chat || !db)
			return MM_FAIL;

		/* make sure table exists */
		init_db();
		cmd->AddCommand("alias", Calias, ALLARENAS, alias_help);
		cmd->AddCommand("qip", Cqip, ALLARENAS, qip_help);
		cmd->AddCommand("rawquery", Crawquery, ALLARENAS, rawquery_help);
		cmd->AddCommand("last", Clast, ALLARENAS, last_help);

		mm->RegCallback(CB_PLAYERACTION, playera, ALLARENAS);

		return MM_OK;
	}
	else if (action == MM_UNLOAD)
	{
		mm->UnregCallback(CB_PLAYERACTION, playera, ALLARENAS);
		cmd->RemoveCommand("alias",Calias, ALLARENAS);
		cmd->RemoveCommand("qip", Cqip, ALLARENAS);
		cmd->RemoveCommand("rawquery", Crawquery, ALLARENAS);
		cmd->RemoveCommand("last", Clast, ALLARENAS);

		mm->ReleaseInterface(pd);
		mm->ReleaseInterface(lm);
		mm->ReleaseInterface(cfg);
		mm->ReleaseInterface(cmd);
		mm->ReleaseInterface(chat);
		mm->ReleaseInterface(net);
		mm->ReleaseInterface(chatnet);
		mm->ReleaseInterface(db);
		return MM_OK;
	}
	return MM_FAIL;
}
Esempio n. 14
0
JournalStore* journal_store_open(JamAccount *acc, gboolean create, GError **err) {
	JournalStore *js = NULL;
	char *path = NULL;
	sqlite3 *db = NULL;
	int ret;
	gboolean exists;

	path = conf_make_account_path(acc, "journal.db");
	exists = g_file_test(path, G_FILE_TEST_EXISTS);

	if (!exists && !create) {
		g_set_error(err, 0, 0, "No offline copy of this journal.");
		goto out;
	}

	if (!verify_path(path, FALSE, &err))
		goto out;

	ret = sqlite3_open(path, &db);
	if (ret != SQLITE_OK) {
		g_set_error(err, 0, 0, "sqlite error %d: %s", ret, sqlite3_errmsg(db));
		goto out;
	}

	sqlite3_trace(db, sql_trace, NULL);

	if (exists) {
		if (!check_version(db)) {
			g_set_error(err, 0, 0,
					"The on-disk journal version differs from "
					"the version understood by this version of LogJam.  "
					"You need to resynchronize your journal.");
			goto out;
		}
	} else {
		if (!init_db(db, err))
			goto out;
	}

	js = g_new0(JournalStore, 1);
	js->account = acc;
	js->db = db;

out:
	g_free(path);
	if (!js && db) sqlite3_close(db);
	return js;
}
Esempio n. 15
0
void Init_tokyo_messenger(){
  mTokyoMessenger = rb_define_module("TokyoMessenger");
  eTokyoMessengerError = rb_define_class("TokyoMessengerError", rb_eStandardError);
  init_mod();

  cDB = rb_define_class_under(mTokyoMessenger, "DB", rb_cObject);
  rb_include_module(cDB, mTokyoMessenger);
  init_db();

  cTable = rb_define_class_under(mTokyoMessenger, "Table", rb_cObject);
  rb_include_module(cTable, mTokyoMessenger);
  init_table();

  cQuery = rb_define_class_under(mTokyoMessenger, "Query", rb_cObject);
  init_query();
}
Esempio n. 16
0
int main(int argc, char *argv[])
{
    if (!fx_init())
    {
        fprintf(stderr, "init the libfetion fail \n");
        exit(0);
    }
    init_db();

    #ifdef WIN32
    #else
        //compatible old app's config file
        moveOldConfigFile();
    #endif

    QApplication app(argc, argv);
    QCoreApplication::addLibraryPath(QCoreApplication::applicationDirPath());

#ifdef HAVE_LOG4QT_DEBUG_ENABLED
    /*FIXME: real log4qt configuration path */
    Log4Qt::PropertyConfigurator::configure(
            app.applicationDirPath() + "/log4qt.properties");
#endif
    QTranslator translator_fetion;
    translator_fetion.load("fetion_utf8_CN", defaultResPath());
    QTranslator translator_qt;
    translator_qt.load("qt_zh_CN", defaultResPath());
    app.installTranslator(&translator_fetion);
    app.installTranslator(&translator_qt);

    app.setFont(Settings::instance().getCurrentFont());
    setSkins(Settings::instance().SkinPath(), Settings::instance().SkinName());
    FxMain *mainWin = new FxMain();

    app.setQuitOnLastWindowClosed(false);
    int reslut = app.exec();

    if (mainWin)
    {
        delete mainWin;
    }

    destoy_db();
    //destroy the libfetion
    fx_terminate();
    return reslut;
}
Esempio n. 17
0
File: main.c Progetto: laminic/cs
int main (int argc, char *argv[])
{

	GtkBuilder *login;
	GtkBuilder *builder;

	GtkWidget  *loginwindow;
    GtkWidget  *window;

	GtkButton 	*loginbtn;


    gtk_init( &argc, &argv );

    /* Create builder */

	builder = gtk_builder_new();
    gtk_builder_add_from_file( builder, "ui.glade", NULL );
    window   = GTK_WIDGET( gtk_builder_get_object( builder, "window1" ) );

	login = gtk_builder_new();
	gtk_builder_add_from_file(login, "login.glade", NULL);
	loginwindow = GTK_WIDGET(gtk_builder_get_object(login, "loginwindow"));

	loginbtn = GTK_BUTTON(gtk_builder_get_object(login, "loginbtn"));
	g_signal_connect(loginbtn, "clicked", G_CALLBACK(cb_login_button), NULL);

	init_db();
	init_login(login, loginwindow, window);
	init_user(builder);
	init_material(builder);
	init_auth(builder);
	init_inout(builder);

    gtk_builder_connect_signals( login, NULL);
    g_object_unref( G_OBJECT( login) );

    gtk_builder_connect_signals( builder, NULL);
    g_object_unref( G_OBJECT( builder ) );


	gtk_widget_show(loginwindow);

    gtk_main();

    return( 0 );
}
Esempio n. 18
0
int main(void)
{
	// initialisiere die DB
	init_db();
  read_lebenslauf();
/*
		print_ort();
		gets(answer);
    doAverage(answer);

		[> Close and deallocate all DBPROCESS structures, clean up <]

		[> dbexit(STDEXIT); <]<]
*/
	dbexit();
	exit(STDEXIT);
}
Esempio n. 19
0
int main(int argc, char *argv[])
{
  if (!init_db()) { exit(1); }

  ib_crsr_t crsr, index_crsr;
  ib_tpl_t tpl;
  ib_err_t err;
  char *l6_orderkey_rle = "l5_customer_key_rle";
  char cstore_l6_orderkey_rle[64];
  sprintf(cstore_l6_orderkey_rle, "%s/%s", db_name, l6_orderkey_rle);
  ib_trx_t ib_trx = ib_trx_begin(IB_TRX_REPEATABLE_READ);
  err = ib_cursor_open_table(cstore_l6_orderkey_rle, ib_trx, &crsr);
  if (err != DB_SUCCESS) { std::cout << ib_strerror(err) << " " << cstore_l6_orderkey_rle << std::endl; }
  err = ib_cursor_open_index_using_name(crsr, "SECONDARY_KEY", &index_crsr);
  if (err != DB_SUCCESS) { std::cout << ib_strerror(err) << std::endl; }

  ib_cursor_set_cluster_access(index_crsr);
  ib_tpl_t key = ib_sec_search_tuple_create(index_crsr);
  ib_tuple_write_u32(key, 0, 330575);
  int res;
  err = ib_cursor_moveto(index_crsr, key, IB_CUR_GE, &res);
  std::cout << "res: " << res << std::endl;
  assert(err == DB_SUCCESS || err == DB_END_OF_INDEX || err == DB_RECORD_NOT_FOUND);
  tpl = ib_clust_read_tuple_create(crsr);
  while (err == DB_SUCCESS) {
    err = ib_cursor_read_row(index_crsr, tpl);
    if (err == DB_RECORD_NOT_FOUND || err == DB_END_OF_INDEX) {
      std::cerr << "not found" << std::endl;
    }
    ib_u32_t orderkey, pos, freq;
    ib_tuple_read_u32(tpl, 0, &orderkey);
    ib_tuple_read_u32(tpl, 1, &pos);
    ib_tuple_read_u32(tpl, 2, &freq);
    std::cout << "orderkey: " << orderkey << ", pos: " << pos << ", freq: " << freq << std::endl;
    err = ib_cursor_next(index_crsr);
    tpl = ib_tuple_clear(tpl);
    break;
  }
  ib_cursor_close(index_crsr); 
  ib_cursor_close(crsr); 
  ib_trx_commit(ib_trx);

  fin_db();

  return 0;
}
Esempio n. 20
0
/**
 * Creates a new registry object. To start using a registry, one must first be
 * attached with `reg_attach`.
 *
 * @param [out] regPtr address of the allocated registry
 * @param [out] errPtr on error, a description of the error that occurred
 * @return             true if success; false if failure
 */
int reg_open(reg_registry** regPtr, reg_error* errPtr) {
    reg_registry* reg = malloc(sizeof(reg_registry));
    if (!reg) {
        return 0;
    }
    if (sqlite3_open(NULL, &reg->db) == SQLITE_OK) {
        if (init_db(reg->db, errPtr)) {
            reg->status = reg_none;
            *regPtr = reg;
            return 1;
        }
    } else {
        reg_sqlite_error(reg->db, errPtr, NULL);
    }
    sqlite3_close(reg->db);
    free(reg);
    return 0;
}
Esempio n. 21
0
int  main( int argc, char** argv ){

    struct  stat  sb;
    loglevel = 5;

    unlink( FILEDB );
    assert( dbset_file( FILEDB, NULL ) ) ;
    assert( init_db( FILEDB ) );

    assert( stat( FILEDB, &sb) != -1 );
    assert( sb.st_size > 1024 );
    assert( unlink( FILEDB ) != -1 );

    assert( dbget_version( ) > 0 );
    

    exit( EXIT_SUCCESS );
}
Esempio n. 22
0
/*
 * remove a person from the database, given the name
 * if the name is not found, don't do anything
 */
void remove_record(char* name) {
    int dbfile = init_db();
    int record_count = 0;
    int total = 0;
    PhoneRecord phone_record, last_record;
    
    // how many entries altogether?
    lseek(dbfile, 0, SEEK_SET);
    read(dbfile, &total, sizeof(int));
    if (total == 0) {
        return;
    }
    
    record_count = total;
    // read the last entry, this might be used to "fill a gap"
    set_to_record(dbfile, total);
    read(dbfile, &last_record, sizeof(PhoneRecord));
    
    // go through all entries, starting at the end
    // if you find the person, override the entry with last person's entry and return
    do {
        set_to_record(dbfile, record_count);
        read(dbfile, &phone_record, sizeof (PhoneRecord));
        
        if (!strcmp(phone_record.name, name)) {
            // are we at the end? we don't need to override the last person with itself ...
            // when we have many entries, we might just omit this
            if (total != record_count) {
                set_to_record(dbfile, record_count);
                write(dbfile, &last_record, sizeof (PhoneRecord));
            }
            lseek(dbfile, 0, SEEK_SET);
            total--;
            write(dbfile, &total, sizeof (int));
            truncate(DB, (sizeof(int)+(total*sizeof(PhoneRecord))));
            printf("[remove] - person %s removed, %d record(s) remaining\n", phone_record.name, total);
            
            return;
        }
    } while(--record_count);
        
    printf("[remove] - person %s is not in the database\n", name);
}
Esempio n. 23
0
int main()
{
    TPW_CONTEXT tpw_context;
    create_context(&tpw_context, uid, auth, len);
    init_db();
    BYTE md[20];
    int ll;
    TPW_RESULT result;

    //init_hash_by_dir(&tpw_context, "/home/wengsht/t");
    
    result = verify_by_filename(&tpw_context, "/home/wengsht/t/1.txt");
    printf("%d\n", result);

    close_context(&tpw_context);
    close_db();

    return 0;
}
Esempio n. 24
0
int main(void)
{
	int len;
	char *lenstr,poststr[512];
	int open_id;
	char *key;
	
	init_db((char *)"127.0.0.1", 3306, (char *)"sanguo", (char *)"root", (char *)"123456");
	
	printf("Content-Type:text/html\n\n");
//        printf("<HTML>\n");
//        printf("<HEAD>\n<TITLE >ost Method</TITLE>\n</HEAD>\n");
//        printf("<BODY>\n");
	lenstr=getenv("CONTENT_LENGTH");
	if(lenstr == NULL) {
		printf("<DIV STYLE=\"COLOR:RED\">Errorarameters should be entered!</DIV>\n");
		return (0);
	}
	len=atoi(lenstr) + 1;
	if (len >= 512)
		return (0);
	
	fgets(poststr,len,stdin);
	parse_post_data(poststr, len);
	key = get_value((char *)"key");
	open_id = atoi(get_value((char *)"open_id"));				
	
	if (!key || open_id == 0) {
		printf("{\"result\":1,\n");
		goto done;
	}
	
	if (check_key_valid(open_id, key) == 0)
		printf("{\"result\":0,\n");
	else
		printf("{\"result\":1,\n");
//        printf("</BODY>\n");
//        printf("</HTML>\n");
done:	
	fflush(stdout);
	close_db();		
	return 0;
}
Esempio n. 25
0
/*
 * add an entry
 */
void add_record(PhoneRecord* phone_record) {
    int dbfile = init_db();
    int record_count;
    
    // read number of entries
    lseek(dbfile, 0, SEEK_SET);
    read(dbfile, &record_count, sizeof(int));
    
    // set pointer after the last entry and append new person
    set_to_record(dbfile, record_count + 1);
    write(dbfile, phone_record, sizeof (PhoneRecord));
    
    // update the record number
    record_count++;
    lseek(dbfile, 0, SEEK_SET);
    write(dbfile, &record_count, sizeof(int));
    
    printf("[add] - added %s, phone number: %ld, number of entries: %d\n", phone_record->name, phone_record->phone_number, record_count);
}
Esempio n. 26
0
BOOL WINAPI DllMain(
	HINSTANCE hinstDLL,  
	DWORD fdwReason,     
	LPVOID lpReserved)  
{
	switch (fdwReason)
	{
	case DLL_PROCESS_ATTACH:
		init_db();
		break;
	case DLL_THREAD_ATTACH:
		break;
	case DLL_THREAD_DETACH:
		break;
	case DLL_PROCESS_DETACH:
		break;
	}
	return TRUE;  
}
Esempio n. 27
0
int main(int argc, char *argv[])
{
	client_t *c;
	int clientCtr = 0;
	char command[256];
	run_threads = 1;
	if (pthread_mutex_init(&run_lock, NULL) != 0) {
		printf("\n run_lock mutex init failed\n");
		return;
	}

	if (pthread_cond_init(&ready_to_run, NULL) != 0) {
		printf("\n run condition variable init failed\n");
		return;
	}
	init_db();

	if (argc != 1) {
		fprintf(stderr, "Usage: server\n");
		exit(1);
	}

	while(1) {
		scanf("%s", command);
		if(strcmp(command, "e") == 0){
			c = client_create(clientCtr++);
			pthread_t *theThread = &(c->thread);
			pthread_create(theThread, NULL, client_run, (void *)c);
		}
		else if(strcmp(command, "s") == 0){
			pthread_mutex_lock(&run_lock);
			run_threads = 0;
			pthread_mutex_unlock(&run_lock);
		} else if(strcmp(command, "g") == 0){
			pthread_mutex_lock(&run_lock);
			run_threads = 1;
			pthread_cond_broadcast(&ready_to_run);
			pthread_mutex_unlock(&run_lock);
		}
	}
	return 0;
}
Esempio n. 28
0
  Status do_start_up() {
    scheduler_ = std::make_unique<ConcurrentScheduler>();
    scheduler_->init(1);

    auto guard = scheduler_->get_current_guard();

    string sql_db_name = "testdb.sqlite";
    sql_connection_ = std::make_shared<SqliteConnectionSafe>(sql_db_name);
    auto &db = sql_connection_->get();
    TRY_STATUS(init_db(db));

    db.exec("BEGIN TRANSACTION").ensure();
    // version == 0 ==> db will be destroyed
    TRY_STATUS(init_messages_db(db, 0));
    db.exec("COMMIT TRANSACTION").ensure();

    messages_db_sync_safe_ = create_messages_db_sync(sql_connection_);
    messages_db_async_ = create_messages_db_async(messages_db_sync_safe_, 0);
    return Status::OK();
  }
Esempio n. 29
0
main ()
{
   char choice;

   init_db ();                          /* initialize "database" */
   while (1)
   {
      choice = menu_sel ();
      switch (choice)
      {
         case 1: add_entry ();
                 break;
         case 2: del_entry ();
                 break;
         case 3: list_db ();
                 break;
         case 4: exit (0);              /* exit the program */

      } /* switch */
   } /* while */
} /* main */
Esempio n. 30
0
static int child_init(int rank) {
	struct dbops_action *p, *p2;
	if (rank!=PROC_INIT && rank != PROC_MAIN && rank != PROC_TCP_MAIN) {
		for (p=dbops_actions; p; p=p->next) {
			for (p2=dbops_actions; p!=p2; p2=p2->next) {  /* check if database is already opened */
				if (strcmp(p->db_url, p2->db_url) == 0) {
					p->ctx = p2->ctx;
					break;
				}
			}

			/* FIXME: Initialize database layer here */

			if (init_db(p) < 0) {
				ERR(MODULE_NAME": CHILD INIT #err\n");

				return -1;
			}
		}
	}
	return 0;
}