예제 #1
0
파일: bson.cpp 프로젝트: w1nk/node-mongodb
void
encodeArray(bson_buffer *bb, const char *name, const Local<Value> element) {
    Local<Array> a = Array::Cast(*element);
    bson_buffer *arr = bson_append_start_array(bb, name);

    for (int i = 0, l=a->Length(); i < l; i++) {
        Local<Value> val = a->Get(Number::New(i));
        stringstream keybuf;
        string keyval;
        keybuf << i << endl;
        keybuf >> keyval;

        if (val->IsString()) {
            encodeString(arr, keyval.c_str(), val);
        }
        else if (val->IsInt32()) {
            encodeInteger(arr, keyval.c_str(), val);
        }
        else if (val->IsNumber()) {
            encodeNumber(arr, keyval.c_str(), val);
        }
        else if (val->IsBoolean()) {
            encodeBoolean(arr, keyval.c_str(), val);
        }
        else if (val->IsArray()) {
            encodeArray(arr, keyval.c_str(), val);
        }
        else if (val->IsObject()) {
            bson bson(encodeObject(val));
            bson_append_bson(arr, keyval.c_str(), &bson);
            bson_destroy(&bson);
        }
    }
    bson_append_finish_object(arr);
}
예제 #2
0
static void WriteTestVal(Local<String> propname, Local<Value> v, const AccessorInfo &info) {
  do_check_true(!propname.IsEmpty());
  do_check_true(v->IsInt32());
  do_check_true(!info.Data().IsEmpty());
  do_check_true(info.Data()->IsInt32());
  test_val = v->Int32Value();
  int offset = info.Data()->Int32Value();
  test_val += offset;
}
예제 #3
0
void FieldDefn::precisionSetter(Local<String> property, Local<Value> value, const AccessorInfo &info)
{
	HandleScope scope;
	FieldDefn *def = ObjectWrap::Unwrap<FieldDefn>(info.This());
	if(!value->IsInt32()){
		NODE_THROW("precision must be an integer");
		return;
	}
	def->this_->SetPrecision(value->IntegerValue());
}
예제 #4
0
void FeatureDefn::geomTypeSetter(Local<String> property, Local<Value> value, const AccessorInfo &info)
{
	HandleScope scope;
	FeatureDefn *def = ObjectWrap::Unwrap<FeatureDefn>(info.This());
	if(!value->IsInt32()){
		NODE_THROW("geomType must be an integer");
		return;
	}
	def->this_->SetGeomType(OGRwkbGeometryType(value->IntegerValue()));
}
예제 #5
0
void Msg_Struct::build_http_msg_buffer(Isolate* isolate, v8::Local<v8::Object> object, std::string &str) {
    std::stringstream stream;
    for(std::vector<Field_Info>::const_iterator iter = field_vec().begin();
            iter != field_vec().end(); iter++) {
        stream.str("");
        stream << "\"" << iter->field_name << "\":";
        Local<Value> value = object->Get(isolate->GetCurrentContext(), String::NewFromUtf8(isolate, iter->field_name.c_str(), NewStringType::kNormal).ToLocalChecked()).ToLocalChecked();
        if(iter->field_type == "int8" || iter->field_type == "int16" ||
                iter->field_type == "int32") {
            int32_t val = 0;
            if (value->IsInt32()) {
                val = value->Int32Value(isolate->GetCurrentContext()).FromJust();
            }
            stream << val << ",";
        }
        else if(iter->field_type == "int64") {
            int64_t val = 0;
            if (value->IsNumber()) {
                val = value->NumberValue(isolate->GetCurrentContext()).FromJust();
            }
            stream << val << ",";
        }
        else if(iter->field_type == "double") {
            double val = 0;
            if (value->IsNumber()) {
                val = value->NumberValue(isolate->GetCurrentContext()).FromJust();
            }
            stream << val << ",";
        }
        else if(iter->field_type == "bool") {
            bool val = 0;
            if (value->IsBoolean()) {
                val = value->BooleanValue(isolate->GetCurrentContext()).FromJust();
            }
            stream << val << ",";
        }
        else if(iter->field_type == "string") {
            if (value->IsString()) {
                String::Utf8Value str(value->ToString(isolate->GetCurrentContext()).ToLocalChecked());
                stream << "\"" << ToCString(str) << "\",";
            } else {
                stream << "\"\",";
            }
        }
        else {
            LOG_ERROR("Can not find the field_type:%s, struct_name:%s", iter->field_type.c_str(), struct_name().c_str());
        }

        str += stream.str();
    }
}
static void Set_DialogState_borders(Local<String> property, Local<Value> value, const AccessorInfo& info)
{
    HandleScope scope;

    Local<Object> self = info.Holder();
    Local<External> wrap = Local<External>::Cast(self->GetInternalField(0));
    if (wrap.IsEmpty())
        return;

    DialogState *tmp = (DialogState *) wrap->Value();
    if (tmp == NULL)
        return;

    if (!value.IsEmpty() && value->IsInt32())
        tmp->getBorders()->setAll(value->Int32Value());
}
예제 #7
0
Handle<Value>
Session::Request(const Arguments& args)
{
    HandleScope scope;

    if (args.Length() < 1 || !args[0]->IsString()) {
        return ThrowException(Exception::Error(String::New(
                "Service URI string must be provided as first parameter.")));
    }
    if (args.Length() < 2 || !args[1]->IsString()) {
        return ThrowException(Exception::Error(String::New(
                "String request name must be provided as second parameter.")));
    }
    if (args.Length() < 3 || !args[2]->IsObject()) {
        return ThrowException(Exception::Error(String::New(
                "Object containing request parameters must be provided "
                "as third parameter.")));
    }
    if (args.Length() < 4 || !args[3]->IsInt32()) {
        return ThrowException(Exception::Error(String::New(
                "Integer correlation identifier must be provided "
                "as fourth parameter.")));
    }
    if (args.Length() >= 5 && !args[4]->IsUndefined() && !args[4]->IsString()) {
        return ThrowException(Exception::Error(String::New(
                "Optional request label must be a string.")));
    }
    if (args.Length() > 5) {
        return ThrowException(Exception::Error(String::New(
                "Function expects at most five arguments.")));
    }

    int cidi = args[3]->Int32Value();

    Session* session = ObjectWrap::Unwrap<Session>(args.This());

    BLPAPI_EXCEPTION_TRY

    Local<String> uri = args[0]->ToString();
    String::AsciiValue uriv(uri);

    blpapi::Service service = session->d_session->getService(*uriv);

    Local<String> name = args[1]->ToString();
    String::Utf8Value namev(name);

    blpapi::Request request = service.createRequest(*namev);

    // Loop over object properties, appending/setting into the request.
    Local<Object> obj = args[2]->ToObject();
    Local<Array> props = obj->GetPropertyNames();

    for (std::size_t i = 0; i < props->Length(); ++i) {
        // Process the key.
        Local<Value> keyval = props->Get(i);
        Local<String> key = keyval->ToString();
        String::Utf8Value keyv(key);

        // Process the value.
        //
        // The values present on the outer object are marshalled into the
        // blpapi::Request by setting values using 'set'.  Arrays indicate
        // values which should be marshalled using 'append'.
        Local<Value> val = obj->Get(keyval);
        if (val->IsString()) {
            Local<String> s = val->ToString();
            String::Utf8Value valv(s);
            request.set(*keyv, *valv);
        } else if (val->IsBoolean()) {
            request.set(*keyv, val->BooleanValue());
        } else if (val->IsNumber()) {
            request.set(*keyv, val->NumberValue());
        } else if (val->IsInt32()) {
            request.set(*keyv, val->Int32Value());
        } else if (val->IsUint32()) {
            request.set(*keyv,
                static_cast<blpapi::Int64>(val->Uint32Value()));
        } else if (val->IsDate()) {
            blpapi::Datetime dt;
            mkdatetime(&dt, val);
            request.set(*keyv, dt);
        } else if (val->IsArray()) {
            // Arrays are marshalled into the blpapi::Request by appending
            // value types using the key of the array in the outer object.
            Local<Object> subarray = val->ToObject();
            int jmax = Array::Cast(*val)->Length();
            for (int j = 0; j < jmax; ++j) {
                Local<Value> subval = subarray->Get(j);
                // Only strings, booleans, and numbers are marshalled.
                if (subval->IsString()) {
                    Local<String> s = subval->ToString();
                    String::Utf8Value subvalv(s);
                    request.append(*keyv, *subvalv);
                } else if (subval->IsBoolean()) {
                    request.append(*keyv, subval->BooleanValue());
                } else if (subval->IsNumber()) {
                    request.append(*keyv, subval->NumberValue());
                } else if (subval->IsInt32()) {
                    request.append(*keyv, subval->Int32Value());
                } else if (subval->IsUint32()) {
                    request.append(*keyv,
                        static_cast<blpapi::Int64>(subval->Uint32Value()));
                } else if (subval->IsDate()) {
                    blpapi::Datetime dt;
                    mkdatetime(&dt, subval);
                    request.append(*keyv, dt);
                } else {
                    return ThrowException(Exception::Error(String::New(
                                "Array contains invalid value type.")));
                }
            }
        } else {
            return ThrowException(Exception::Error(String::New(
                        "Object contains invalid value type.")));
        }
    }

    blpapi::CorrelationId cid(cidi);

    if (args.Length() == 5) {
        String::Utf8Value labelv(args[4]->ToString());
        session->d_session->sendRequest(request, session->d_identity,
                                        cid, 0, *labelv, labelv.length());
    } else {
        session->d_session->sendRequest(request, session->d_identity, cid);
    }

    BLPAPI_EXCEPTION_CATCH_RETURN

    return scope.Close(Integer::New(cidi));
}
예제 #8
0
Handle<Value>
Session::subscribe(const Arguments& args, bool resubscribe)
{
    HandleScope scope;

    if (args.Length() < 1 || !args[0]->IsArray()) {
        return ThrowException(Exception::Error(String::New(
                "Array of subscription information must be provided.")));
    }
    if (args.Length() >= 2 && !args[1]->IsUndefined() && !args[1]->IsString()) {
        return ThrowException(Exception::Error(String::New(
                "Optional subscription label must be a string.")));
    }
    if (args.Length() > 2) {
        return ThrowException(Exception::Error(String::New(
                "Function expects at most two arguments.")));
    }

    blpapi::SubscriptionList sl;

    Local<Object> o = args[0]->ToObject();
    for (std::size_t i = 0; i < Array::Cast(*(args[0]))->Length(); ++i) {
        Local<Value> v = o->Get(i);
        if (!v->IsObject()) {
            return ThrowException(Exception::Error(String::New(
                        "Array elements must be objects "
                        "containing subscription information.")));
        }
        Local<Object> io = v->ToObject();

        // Process 'security' string
        Local<Value> iv = io->Get(String::New("security"));
        if (!iv->IsString()) {
            return ThrowException(Exception::Error(String::New(
                        "Property 'security' must be a string.")));
        }
        String::Utf8Value secv(iv);
        if (0 == secv.length()) {
            return ThrowException(Exception::Error(String::New(
                        "Property 'security' must be a string.")));
        }

        // Process 'fields' array
        iv = io->Get(String::New("fields"));
        if (!iv->IsArray()) {
            return ThrowException(Exception::Error(String::New(
                        "Property 'fields' must be an array of strings.")));
        }
        std::string fields;
        formFields(&fields, iv->ToObject());

        // Process 'options' array
        iv = io->Get(String::New("options"));
        if (!iv->IsUndefined() && !iv->IsNull() && !iv->IsObject()) {
            return ThrowException(Exception::Error(String::New(
                        "Property 'options' must be an object containing "
                        "whose keys and key values will be configured as "
                        "options.")));
        }
        std::string options;
        formOptions(&options, iv);

        // Process 'correlation' int or string
        iv = io->Get(String::New("correlation"));
        if (!iv->IsInt32()) {
            return ThrowException(Exception::Error(String::New(
                        "Property 'correlation' must be an integer.")));
        }
        int correlation = iv->Int32Value();

        sl.add(*secv, fields.c_str(), options.c_str(),
               blpapi::CorrelationId(correlation));
    }

    Session* session = ObjectWrap::Unwrap<Session>(args.This());

    BLPAPI_EXCEPTION_TRY
    if (args.Length() == 2) {
        Local<String> s = args[1]->ToString();
        String::Utf8Value labelv(s);
        if (resubscribe)
            session->d_session->resubscribe(sl, *labelv, labelv.length());
        else
            session->d_session->subscribe(sl, *labelv, labelv.length());
    } else {
        if (resubscribe)
            session->d_session->resubscribe(sl);
        else
            session->d_session->subscribe(sl);
    }
    BLPAPI_EXCEPTION_CATCH_RETURN

    return scope.Close(args.This());
}
bool JsArgToArrayConverter::ConvertArg(const Local<Value>& arg, int index)
{
	bool success = false;
	stringstream s;

	JEnv env;

	Type returnType = JType::getClassType(m_return_type);

	if (arg.IsEmpty())
	{
		s << "Cannot convert empty JavaScript object";
		success = false;
	}
	else if (arg->IsInt32() && (returnType == Type::Int || returnType == Type::Null))
	{
		jint value = arg->Int32Value();
		JniLocalRef javaObject(JType::NewInt(env, value));
		SetConvertedObject(env, index, javaObject);

		success = true;
	}
	else if (arg->IsNumber() || arg->IsNumberObject())
	{
		double d = arg->NumberValue();
		int64_t i = (int64_t)d;
		bool isInteger = d == i;

		if (isInteger)
		{
			jobject obj;

			//if returnType is long it will cast to long
			//if there is no return type specified it will cast to int
			//because default return type is null (ref type)
			if ((INT_MIN <= i) && (i <= INT_MAX) && (returnType == Type::Int || returnType == Type::Null))
			{
				obj = JType::NewInt(env, (jint)d);
			}
			else /*isLong*/
			{
				obj = JType::NewLong(env, (jlong)d);
			}

			JniLocalRef javaObject(obj);
			SetConvertedObject(env, index, javaObject);

			success = true;
		}
		else
		{
			jobject obj;

			//if returnType is double it will cast to double
			//if there is no return type specified it will cast to float
			//because default return type is null (ref type)
			if((FLT_MIN <= d) && (d <= FLT_MAX) && (returnType == Type::Float || returnType == Type::Null)) {
				obj = JType::NewFloat(env, (jfloat)d);
			}
			else {/*isDouble*/
				obj = JType::NewDouble(env, (jdouble)d);
			}

			JniLocalRef javaObject(obj);
			SetConvertedObject(env, index, javaObject);

			success = true;
		}
	}
	else if (arg->IsBoolean())
	{
		jboolean value = arg->BooleanValue();
		JniLocalRef javaObject(JType::NewBoolean(env, value));
		SetConvertedObject(env, index, javaObject);
		success = true;
	}
	else if (arg->IsBooleanObject())
	{
		auto boolObj = Local<BooleanObject>::Cast(arg);
		jboolean value = boolObj->BooleanValue() ? JNI_TRUE : JNI_FALSE;
		JniLocalRef javaObject(JType::NewBoolean(env, value));
		SetConvertedObject(env, index, javaObject);

		success = true;
	}
	else if (arg->IsString() || arg->IsStringObject())
	{
		JniLocalRef stringObject(ConvertToJavaString(arg));
		SetConvertedObject(env, index, stringObject);

		success = true;
	}
	else if (arg->IsObject())
	{
		auto objectWithHiddenID = arg->ToObject();

		auto hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsLong());
		if (!hidden.IsEmpty())
		{
			jlong value = 0;
			if (hidden->IsString())
			{
				auto strValue = ConvertToString(hidden->ToString());
				value = atoll(strValue.c_str());
			}
			else if (hidden->IsInt32())
			{
				value = hidden->ToInt32()->Int32Value();
			}

			JniLocalRef javaObject(JType::NewLong(env, value));
			SetConvertedObject(env, index, javaObject);
			return true;
		}

		hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsByte());
		if (!hidden.IsEmpty())
		{
			jbyte value = 0;
			if (hidden->IsString())
			{
				string value = ConvertToString(hidden->ToString());
				int byteArg = atoi(value.c_str());
				value = (jbyte)byteArg;
			}
			else if (hidden->IsInt32())
			{
				int byteArg = hidden->ToInt32()->Int32Value();
				value = (jbyte)byteArg;
			}

			JniLocalRef javaObject(JType::NewByte(env, value));
			SetConvertedObject(env, index, javaObject);
			return true;
		}

		hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsShort());
		if (!hidden.IsEmpty())
		{
			jshort value = 0;
			if (hidden->IsString())
			{
				string value = ConvertToString(hidden->ToString());
				int shortArg = atoi(value.c_str());
				value = (jshort)shortArg;
			}
			else if (hidden->IsInt32())
			{
				jlong shortArg = hidden->ToInt32()->Int32Value();
				value = (jshort)shortArg;
			}

			JniLocalRef javaObject(JType::NewShort(env, value));
			SetConvertedObject(env, index, javaObject);
			return true;
		}

		hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsDouble());
		if (!hidden.IsEmpty())
		{
			jdouble value = 0;
			if (hidden->IsNumber())
			{
				double doubleArg = hidden->ToNumber()->NumberValue();
				value = (jdouble)doubleArg;
			}

			JniLocalRef javaObject(JType::NewDouble(env, value));
			SetConvertedObject(env, index, javaObject);
			return true;
		}

		hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsFloat());
		if (!hidden.IsEmpty())
		{
			jfloat value = 0;
			if (hidden->IsNumber())
			{
				double floatArg = hidden->ToNumber()->NumberValue();
				value = (jfloat)floatArg;
			}

			JniLocalRef javaObject(JType::NewFloat(env, value));
			SetConvertedObject(env, index, javaObject);
			return true;
		}

		hidden = objectWithHiddenID->GetHiddenValue(V8StringConstants::GetMarkedAsChar());
		if (!hidden.IsEmpty())
		{
			jchar value = '\0';
			if (hidden->IsString())
			{
				string str = ConvertToString(hidden->ToString());
				value = (jchar)str[0];
			}

			JniLocalRef javaObject(JType::NewChar(env, value));
			SetConvertedObject(env, index, javaObject);
			return true;
		}

		jweak obj = ObjectManager::GetJavaObjectByJsObjectStatic(objectWithHiddenID);
		success = obj != nullptr;
		if (success)
		{
			SetConvertedObject(env, index, obj, true);
		}
		else
		{
			s << "Cannot convert JavaScript object with id " << objectWithHiddenID->GetIdentityHash() << " at index " << index;
		}
	}
	else if (arg->IsUndefined() || arg->IsNull())
	{
		SetConvertedObject(env, index, nullptr);
		success = true;
	}
	else
	{
		s << "Cannot convert JavaScript object at index " << index;
		success = false;
	}

	if (!success)
	{
		m_error.index = index;
		m_error.msg = s.str();
	}

	return success;
}
예제 #10
0
    // notification.protocol=
    static void SetProtocol(Local<String> property, Local<Value> value, const AccessorInfo& info) {
      RCSwitchNode* rcswitchNode_instance = node::ObjectWrap::Unwrap<RCSwitchNode>(info.Holder());

      if(value->IsInt32())
        rcswitchNode_instance->rcswitch.setProtocol(value->Int32Value());
    }
예제 #11
0
    bool QueryOperation::BindParameters( Handle<Array> node_params )
    {
        uint32_t count = node_params->Length();

        if( count > 0 ) {

            for( uint32_t i = 0; i < count; ++i ) {

                Local<Value> p = node_params->Get( i );
                ParamBinding binding;

                if( p->IsNull() ) {

                    binding.js_type = ParamBinding::JS_NULL;
                    binding.c_type = SQL_C_CHAR;
                    binding.sql_type = SQL_CHAR;
                    binding.param_size = 1;
                    binding.digits = 0;
                    binding.buffer = NULL;
                    binding.buffer_len = 0;
                    binding.indptr = SQL_NULL_DATA;
                }
                else if( p->IsString() ) {

                    binding.js_type = ParamBinding::JS_STRING;
                    binding.c_type = SQL_C_WCHAR;
                    binding.sql_type = SQL_WVARCHAR;
                    Local<String> str_param = p->ToString();
                    int str_len = str_param->Length();
                    binding.buffer = new uint16_t[ str_len + 1 ];   // null terminator
                    str_param->Write( static_cast<uint16_t*>( binding.buffer ));
                    if( str_len > 4000 ) {
                        binding.param_size = 0;     // max types require 0 precision
                    }
                    else {
                        binding.param_size = str_len;
                    }
                    binding.buffer_len = str_len * sizeof( uint16_t );
                    binding.digits = 0;
                    binding.indptr = binding.buffer_len;
                }
                else if( p->IsBoolean() ) {
                    
                    binding.js_type = ParamBinding::JS_BOOLEAN;
                    binding.c_type = SQL_C_BIT;
                    binding.sql_type = SQL_BIT;
                    binding.buffer = new uint16_t;
                    binding.buffer_len = sizeof( uint16_t );
                    *static_cast<uint16_t*>( binding.buffer ) = p->BooleanValue();
                    binding.param_size = 1;
                    binding.digits = 0;
                    binding.indptr = binding.buffer_len;
                }
                else if( p->IsInt32()) {

                    binding.js_type = ParamBinding::JS_INT;
                    binding.c_type = SQL_C_SLONG;
                    binding.sql_type = SQL_INTEGER;
                    binding.buffer = new int32_t;
                    binding.buffer_len = sizeof( int32_t );
                    *static_cast<int32_t*>( binding.buffer ) = p->Int32Value();
                    binding.param_size = sizeof( int32_t );
                    binding.digits = 0;
                    binding.indptr = binding.buffer_len;
                }
                else if( p->IsUint32()) {

                    binding.js_type = ParamBinding::JS_UINT;
                    binding.c_type = SQL_C_ULONG;
                    binding.sql_type = SQL_BIGINT;
                    binding.buffer = new uint32_t;
                    binding.buffer_len = sizeof( uint32_t );
                    *static_cast<int32_t*>( binding.buffer ) = p->Uint32Value();
                    binding.param_size = sizeof( uint32_t );
                    binding.digits = 0;
                    binding.indptr = binding.buffer_len;
                }
                else if( p->IsNumber()) {

                    // numbers can be either integers or doubles.  We attempt to determine which it is through a simple
                    // cast and equality check
                    double d = p->NumberValue();
                    if( _isnan( d ) || !_finite( d ) ) {

                        return ParameterErrorToUserCallback( i, "Invalid number parameter" );

                    }
                    else if( d == floor( d ) && 
                             d >= std::numeric_limits<int64_t>::min() && 
                             d <= std::numeric_limits<int64_t>::max() ) {

                        binding.js_type = ParamBinding::JS_NUMBER;
                        binding.c_type = SQL_C_SBIGINT;
                        binding.sql_type = SQL_BIGINT;
                        binding.buffer = new int64_t;
                        binding.buffer_len = sizeof( int64_t );
                        *static_cast<int64_t*>( binding.buffer ) = p->IntegerValue();
                        binding.param_size = sizeof( int64_t );
                        binding.digits = 0;
                        binding.indptr = binding.buffer_len;
                    }
                    else {

                        binding.js_type = ParamBinding::JS_NUMBER;
                        binding.c_type = SQL_C_DOUBLE;
                        binding.sql_type = SQL_DOUBLE;
                        binding.buffer = new double;
                        binding.buffer_len = sizeof( double );
                        *static_cast<double*>( binding.buffer ) = p->NumberValue();
                        binding.param_size = sizeof( double );
                        binding.digits = 0;
                        binding.indptr = binding.buffer_len;
                    }
                }
                else if( p->IsDate() ) {

                    // Since JS dates have no timezone context, all dates are assumed to be UTC
                    Handle<Date> dateObject = Handle<Date>::Cast<Value>( p );
                    assert( !dateObject.IsEmpty() );
                    // dates in JS are stored internally as ms count from Jan 1, 1970
                    double d = dateObject->NumberValue();
                    SQL_SS_TIMESTAMPOFFSET_STRUCT* sql_tm = new SQL_SS_TIMESTAMPOFFSET_STRUCT;
                    TimestampColumn sql_date( d );
                    sql_date.ToTimestampOffset( *sql_tm );

                    binding.js_type = ParamBinding::JS_DATE;
                    binding.c_type = SQL_C_BINARY;
                    // TODO: Determine proper SQL type based on version of server we're talking to
                    binding.sql_type = SQL_SS_TIMESTAMPOFFSET;
                    binding.buffer = sql_tm;
                    binding.buffer_len = sizeof( SQL_SS_TIMESTAMPOFFSET_STRUCT );
                    // TODO: Determine proper precision and size based on version of server we're talking to
                    binding.param_size = SQL_SERVER_2008_DEFAULT_DATETIME_PRECISION;
                    binding.digits = SQL_SERVER_2008_DEFAULT_DATETIME_SCALE;
                    binding.indptr = binding.buffer_len;
                }
                else if( p->IsObject() && node::Buffer::HasInstance( p )) {

                    // TODO: Determine if we need something to keep the Buffer object from going
                    // away while we use it we could just copy the data, but with buffers being 
                    // potentially very large, that could be problematic
                    Local<Object> o = p.As<Object>();
                    
                    binding.js_type = ParamBinding::JS_BUFFER;
                    binding.c_type = SQL_C_BINARY;
                    binding.sql_type = SQL_VARBINARY;
                    binding.buffer = node::Buffer::Data( o );
                    binding.buffer_len = node::Buffer::Length( o );
                    binding.param_size = binding.buffer_len;
                    binding.digits = 0;
                    binding.indptr = binding.buffer_len;
                }

                else {


                    return ParameterErrorToUserCallback( i, "Invalid parameter type" );

                }

                params.push_back( move( binding ));
            }
        }

        return true;
    }
예제 #12
0
Parameter* ODBC::GetParametersFromArray (Local<Array> values, int *paramCount) {
  DEBUG_PRINTF("ODBC::GetParametersFromArray\n");
  *paramCount = values->Length();
  
  Parameter* params = (Parameter *) malloc(*paramCount * sizeof(Parameter));

  for (int i = 0; i < *paramCount; i++) {
    Local<Value> value = values->Get(i);
    
    params[i].size          = 0;
    params[i].length        = SQL_NULL_DATA;
    params[i].buffer_length = 0;
    params[i].decimals      = 0;

    DEBUG_PRINTF("ODBC::GetParametersFromArray - &param[%i].length = %X\n",
                 i, &params[i].length);

    if (value->IsString()) {
      Local<String> string = value->ToString();
      int length = string->Length();
      
      params[i].c_type        = SQL_C_TCHAR;
#ifdef UNICODE
      params[i].type          = (length >= 8000) ? SQL_WLONGVARCHAR : SQL_WVARCHAR;
      params[i].buffer_length = (length * sizeof(uint16_t)) + sizeof(uint16_t);
#else
      params[i].type          = (length >= 8000) ? SQL_LONGVARCHAR : SQL_VARCHAR;
      params[i].buffer_length = string->Utf8Length() + 1;
#endif
      params[i].buffer        = malloc(params[i].buffer_length);
      params[i].size          = params[i].buffer_length;
      params[i].length        = SQL_NTS;//params[i].buffer_length;

#ifdef UNICODE
      string->Write((uint16_t *) params[i].buffer);
#else
      string->WriteUtf8((char *) params[i].buffer);
#endif

      DEBUG_PRINTF("ODBC::GetParametersFromArray - IsString(): params[%i] "
                   "c_type=%i type=%i buffer_length=%i size=%i length=%i "
                   "value=%s\n", i, params[i].c_type, params[i].type,
                   params[i].buffer_length, params[i].size, params[i].length, 
                   (char*) params[i].buffer);
    }
    else if (value->IsNull()) {
      params[i].c_type = SQL_C_DEFAULT;
      params[i].type   = SQL_VARCHAR;
      params[i].length = SQL_NULL_DATA;

      DEBUG_PRINTF("ODBC::GetParametersFromArray - IsNull(): params[%i] "
                   "c_type=%i type=%i buffer_length=%i size=%i length=%i\n",
                   i, params[i].c_type, params[i].type,
                   params[i].buffer_length, params[i].size, params[i].length);
    }
    else if (value->IsInt32()) {
      int64_t  *number = new int64_t(value->IntegerValue());
      params[i].c_type = SQL_C_SBIGINT;
      params[i].type   = SQL_BIGINT;
      params[i].buffer = number;
      params[i].length = 0;
      
      DEBUG_PRINTF("ODBC::GetParametersFromArray - IsInt32(): params[%i] "
                   "c_type=%i type=%i buffer_length=%i size=%i length=%i "
                   "value=%lld\n", i, params[i].c_type, params[i].type,
                   params[i].buffer_length, params[i].size, params[i].length,
                   *number);
    }
    else if (value->IsNumber()) {
      double *number   = new double(value->NumberValue());
      
      params[i].c_type        = SQL_C_DOUBLE;
      params[i].type          = SQL_DECIMAL;
      params[i].buffer        = number;
      params[i].buffer_length = sizeof(double);
      params[i].length        = params[i].buffer_length;
      params[i].decimals      = 7;
      params[i].size          = sizeof(double);

      DEBUG_PRINTF("ODBC::GetParametersFromArray - IsNumber(): params[%i] "
                  "c_type=%i type=%i buffer_length=%i size=%i length=%i "
		  "value=%f\n",
                  i, params[i].c_type, params[i].type,
                  params[i].buffer_length, params[i].size, params[i].length,
		  *number);
    }
    else if (value->IsBoolean()) {
      bool *boolean    = new bool(value->BooleanValue());
      params[i].c_type = SQL_C_BIT;
      params[i].type   = SQL_BIT;
      params[i].buffer = boolean;
      params[i].length = 0;
      
      DEBUG_PRINTF("ODBC::GetParametersFromArray - IsBoolean(): params[%i] "
                   "c_type=%i type=%i buffer_length=%i size=%i length=%i\n",
                   i, params[i].c_type, params[i].type,
                   params[i].buffer_length, params[i].size, params[i].length);
    }
  } 
  
  return params;
}
예제 #13
0
bool CQueryParameter::TransformParameter( Isolate* isolate, Local< Value > value, sBindParameter** pOutParam )
{
	HandleScope scope( isolate );
	Local< Context > context = isolate->GetCurrentContext( );

	sBindParameter* pParameter = *pOutParam;

	if( value->IsNull( ) )
	{
		pParameter->SetNull( );
	}
	else if( value->IsString( ) )
	{
		pParameter->SetString( value.As<String>( ) );
	}
	else if( value->IsBoolean( ) )
	{
		pParameter->SetBool( value->BooleanValue( context ).FromJust( ) );
	}
	else if( value->IsInt32( ) )
	{
		pParameter->SetInt( value->Int32Value( context ).FromJust( ) );
	}
	else if( value->IsUint32( ) )
	{
		pParameter->SetUInt( value->Uint32Value( context ).FromJust( ) );
	}
	else if( value->IsNumber( ) )
	{
		double d = value->NumberValue( context ).FromJust( );
		if( _isnan( d ) || !_finite( d ) )
		{
			return false;
		}
		else if( d == floor( d ) &&
				 d >= std::numeric_limits<int64_t>::min( ) &&
				 d <= std::numeric_limits<int64_t>::max( )
				 )
		{
			pParameter->SetInt64( value->IntegerValue( context ).FromJust( ) );
		}
		else
		{
			pParameter->SetDouble( value->NumberValue( context ).FromJust( ) );
		}
	}
	else if( value->IsDate( ) )
	{
		Local<Date> dateObject = value.As<Date>( );

		pParameter->SetDate( dateObject->NumberValue( context ).FromJust( ) );
	}
	else if( value->IsObject( ) )
	{
		Local<Object> objValue = value.As<Object>( );

		if( node::Buffer::HasInstance( value ) )
		{
			pParameter->SetBuffer( isolate, objValue );
		}
		else
		{
			Local< String > strId = String::NewFromUtf8( isolate, "_objId", NewStringType::kNormal ).ToLocalChecked( );


			if( objValue->HasRealNamedProperty( context, strId ).FromJust( ) )
			{
				Local< Uint32 > numTypeId = objValue->Get( context, strId ).ToLocalChecked( ).As< Uint32 >( );

				uint32_t nType = numTypeId->Int32Value( context ).FromJust( );

				switch( nType )
				{
					case ID_INPUT_STREAM:
					{
						Local<Value> type = objValue->Get(
							context, String::NewFromUtf8( isolate, "type", NewStringType::kNormal ).ToLocalChecked( )
						).ToLocalChecked( );

						Local<Value> stream = objValue->Get(
							context, String::NewFromUtf8( isolate, "stream", NewStringType::kNormal ).ToLocalChecked( )
						).ToLocalChecked( );

						Local<Value> length = objValue->Get(
							context, String::NewFromUtf8( isolate, "length", NewStringType::kNormal ).ToLocalChecked( )
						).ToLocalChecked( );

						pParameter->SetStream( isolate, type->Uint32Value( context ).FromJust( ), stream, static_cast< SQLUINTEGER >( length->IntegerValue( context ).FromJust( ) ) );

						break;
					}
					case ID_NUMERIC_VALUE:
					{
						Local< Value > precision = objValue->Get(
							context, String::NewFromUtf8( isolate, "precision", NewStringType::kNormal ).ToLocalChecked( )
						).ToLocalChecked( );

						Local<Value> scale = objValue->Get(
							context, String::NewFromUtf8( isolate, "scale", NewStringType::kNormal ).ToLocalChecked( )
						).ToLocalChecked( );

						Local<Value> sign = objValue->Get(
							context, String::NewFromUtf8( isolate, "sign", NewStringType::kNormal ).ToLocalChecked( )
						).ToLocalChecked( );

						Local<Value> value = objValue->Get(
							context, String::NewFromUtf8( isolate, "value", NewStringType::kNormal ).ToLocalChecked( )
						).ToLocalChecked( );

						Local< Uint32 > numPrecision = precision.As<Uint32>( );
						Local< Uint32 > numScale = scale.As<Uint32>( );
						Local< Boolean > boolSign = sign.As<Boolean>( );
						Local< ArrayBuffer > arrBuffer = ( value.As<Uint8Array>( ) )->Buffer( );

						ArrayBuffer::Contents contents = arrBuffer->GetContents( );

						if( contents.ByteLength( ) > SQL_MAX_NUMERIC_LEN )
						{
							return false;
						}

						pParameter->SetNumeric( numPrecision->Uint32Value( context ).FromJust( ),
												numScale->Uint32Value( context ).FromJust( ),
												boolSign->BooleanValue( context ).FromJust( ),
												contents.Data( ),
												contents.ByteLength( )
						);


						break;
					}
					default:
					{
						return false;
					}
				}
			}
			else
			{
				return false;
			}
		}
	}
	else
	{
		return false;
	}

	return true;
}
예제 #14
0
Parameter* ODBC::GetParametersFromArray (Local<Array> values, int *paramCount) {
    DEBUG_PRINTF("ODBC::GetParametersFromArray\n");
    *paramCount = values->Length();

    Parameter* params = NULL;

    if (*paramCount > 0) {
        params = (Parameter *) malloc(*paramCount * sizeof(Parameter));
    }

    for (int i = 0; i < *paramCount; i++) {
        Local<Value> value = values->Get(i);

        params[i].ColumnSize       = 0;
        params[i].StrLen_or_IndPtr = SQL_NULL_DATA;
        params[i].BufferLength     = 0;
        params[i].DecimalDigits    = 0;

        DEBUG_PRINTF("ODBC::GetParametersFromArray - param[%i].length = %lli\n",
                     i, params[i].StrLen_or_IndPtr);

        if (value->IsString()) {
            Local<String> string = value->ToString();
            int length = string->Length();

            params[i].ValueType         = SQL_C_TCHAR;
            params[i].ColumnSize        = 0; //SQL_SS_LENGTH_UNLIMITED
#ifdef UNICODE
            params[i].ParameterType     = SQL_WVARCHAR;
            params[i].BufferLength      = (length * sizeof(uint16_t)) + sizeof(uint16_t);
#else
            params[i].ParameterType     = SQL_VARCHAR;
            params[i].BufferLength      = string->Utf8Length() + 1;
#endif
            params[i].ParameterValuePtr = malloc(params[i].BufferLength);
            params[i].StrLen_or_IndPtr  = SQL_NTS;//params[i].BufferLength;

#ifdef UNICODE
            string->Write((uint16_t *) params[i].ParameterValuePtr);
#else
            string->WriteUtf8((char *) params[i].ParameterValuePtr);
#endif

            DEBUG_PRINTF("ODBC::GetParametersFromArray - IsString(): params[%i] c_type=%i type=%i buffer_length=%lli size=%lli length=%lli value=%s\n",
                         i, params[i].ValueType, params[i].ParameterType,
                         params[i].BufferLength, params[i].ColumnSize, params[i].StrLen_or_IndPtr,
                         (char*) params[i].ParameterValuePtr);
        }
        else if (value->IsNull()) {
            params[i].ValueType = SQL_C_DEFAULT;
            params[i].ParameterType   = SQL_VARCHAR;
            params[i].StrLen_or_IndPtr = SQL_NULL_DATA;

            DEBUG_PRINTF("ODBC::GetParametersFromArray - IsNull(): params[%i] c_type=%i type=%i buffer_length=%lli size=%lli length=%lli\n",
                         i, params[i].ValueType, params[i].ParameterType,
                         params[i].BufferLength, params[i].ColumnSize, params[i].StrLen_or_IndPtr);
        }
        else if (value->IsInt32()) {
            int64_t  *number = new int64_t(value->IntegerValue());
            params[i].ValueType = SQL_C_SBIGINT;
            params[i].ParameterType   = SQL_BIGINT;
            params[i].ParameterValuePtr = number;
            params[i].StrLen_or_IndPtr = 0;

            DEBUG_PRINTF("ODBC::GetParametersFromArray - IsInt32(): params[%i] c_type=%i type=%i buffer_length=%lli size=%lli length=%lli value=%lld\n",
                         i, params[i].ValueType, params[i].ParameterType,
                         params[i].BufferLength, params[i].ColumnSize, params[i].StrLen_or_IndPtr,
                         *number);
        }
        else if (value->IsNumber()) {
            double *number   = new double(value->NumberValue());

            params[i].ValueType         = SQL_C_DOUBLE;
            params[i].ParameterType     = SQL_DECIMAL;
            params[i].ParameterValuePtr = number;
            params[i].BufferLength      = sizeof(double);
            params[i].StrLen_or_IndPtr  = params[i].BufferLength;
            params[i].DecimalDigits     = 7;
            params[i].ColumnSize        = sizeof(double);

            DEBUG_PRINTF("ODBC::GetParametersFromArray - IsNumber(): params[%i] c_type=%i type=%i buffer_length=%lli size=%lli length=%lli value=%f\n",
                         i, params[i].ValueType, params[i].ParameterType,
                         params[i].BufferLength, params[i].ColumnSize, params[i].StrLen_or_IndPtr,
                         *number);
        }
        else if (value->IsBoolean()) {
            bool *boolean = new bool(value->BooleanValue());
            params[i].ValueType         = SQL_C_BIT;
            params[i].ParameterType     = SQL_BIT;
            params[i].ParameterValuePtr = boolean;
            params[i].StrLen_or_IndPtr  = 0;

            DEBUG_PRINTF("ODBC::GetParametersFromArray - IsBoolean(): params[%i] c_type=%i type=%i buffer_length=%lli size=%lli length=%lli\n",
                         i, params[i].ValueType, params[i].ParameterType,
                         params[i].BufferLength, params[i].ColumnSize, params[i].StrLen_or_IndPtr);
        }
    }

    return params;
}
예제 #15
0
 void JSZCluster::checkArgument(const v8::FunctionCallbackInfo<v8::Value> &info, unsigned int index,
                                const std::shared_ptr<ClusterCmdParamsBase> &cmdParam) {
     if (info.Length() <= ((int) index + 1)) {
         stringstream stream;
         stream << EXECUTE_CMD_BY_ID << " needs almost " << index << " arguments where the first is the cmd";
         throw JSException(stream.str());
     }
     Local<v8::Value> arg = info[index + 1];
     switch (cmdParam->getZCLDataType()) {
         case ZCLTypeDataType::ZCLTypeUInt8:
         case ZCLTypeDataType::ZCLTypeUInt16:
         case ZCLTypeDataType::ZCLTypeUInt24:
         case ZCLTypeDataType::ZCLTypeUInt32:
         case ZCLTypeDataType::ZCLTypeUInt40:
         case ZCLTypeDataType::ZCLTypeUInt48:
         case ZCLTypeDataType::ZCLTypeUInt56:
         case ZCLTypeDataType::ZCLTypeUInt64:
             if (!arg->IsUint32()) {
                 stringstream stream;
                 stream << EXECUTE_CMD_BY_ID << " needs as argument " << index << " an unsigned integer";
                 throw JSException(stream.str());
             }
             break;
         case ZCLTypeDataType::ZCLTypeSInt8:
         case ZCLTypeDataType::ZCLTypeSInt16:
         case ZCLTypeDataType::ZCLTypeSInt24:
         case ZCLTypeDataType::ZCLTypeSInt32:
         case ZCLTypeDataType::ZCLTypeSInt40:
         case ZCLTypeDataType::ZCLTypeSInt48:
         case ZCLTypeDataType::ZCLTypeSInt56:
         case ZCLTypeDataType::ZCLTypeSInt64:
             if (!arg->IsInt32()) {
                 stringstream stream;
                 stream << EXECUTE_CMD_BY_ID << " needs as argument " << index << " an integer";
                 throw JSException(stream.str());
             }
             break;
         case ZCLTypeDataType::ZCLTypeIEEEaddress:
         case ZCLTypeDataType::ZCLTypeStringChar:
             if (!arg->IsString()) {
                 stringstream stream;
                 stream << EXECUTE_CMD_BY_ID << " needs as argument " << index << " a string";
                 throw JSException(stream.str());
             }
             break;
         case ZCLTypeDataType::ZCLTypeArray:
             if (!arg->IsUint32Array() && !arg->IsUint32Array()) {
                 if (!arg->IsArray()) {
                     stringstream stream;
                     stream << EXECUTE_CMD_BY_ID << " needs as argument " << index << " an array";
                     throw JSException(stream.str());
                 }
             }
             break;
         default:
             stringstream stream;
             stream << EXECUTE_CMD_BY_ID << " needs as argument " << index << " a type "
                    << cmdParam->getZCLDataType() << " the it is not managed";
             throw JSException(stream.str());
     }
 }
예제 #16
0
Handle<Value> Database::Query(const Arguments& args) {
  HandleScope scope;

  REQ_STR_ARG(0, sql);
  
  Local<Function> cb; 
  
  int paramCount = 0;
  Parameter* params;

  Database* dbo = ObjectWrap::Unwrap<Database>(args.This());

  struct query_request *prep_req = (struct query_request *)
    calloc(1, sizeof(struct query_request));

  if (!prep_req) {
    V8::LowMemoryNotification();
    return ThrowException(Exception::Error(String::New("Could not allocate enough memory")));
  }

  // populate prep_req->params if parameters were supplied
  //
  if (args.Length() > 2) 
  {
      if ( !args[1]->IsArray() )
      {
           return ThrowException(Exception::TypeError(
                      String::New("Argument 1 must be an Array"))
           );
      }
      else if ( !args[2]->IsFunction() )
      {
           return ThrowException(Exception::TypeError(
                      String::New("Argument 2 must be a Function"))
           );
      }
  

      Local<Array> values = Local<Array>::Cast(args[1]);
      cb = Local<Function>::Cast(args[2]);

      prep_req->paramCount = paramCount = values->Length();
      prep_req->params     = params     = new Parameter[paramCount];

      for (int i = 0; i < paramCount; i++)
      {
          Local<Value> value = values->Get(i);

          params[i].size          = 0;
          params[i].length        = NULL;
          params[i].buffer_length = 0;

          if (value->IsString()) 
          {
              String::Utf8Value string(value);
              
              params[i].c_type        = SQL_C_CHAR;
              params[i].type          = SQL_VARCHAR;
              params[i].length        = SQL_NTS;
              params[i].buffer        = malloc(string.length() + 1);
              params[i].buffer_length = string.length() + 1;
              params[i].size          = string.length() + 1;

              strcpy((char*)params[i].buffer, *string);
          }
          else if (value->IsNull()) 
          {
              params[i].c_type = SQL_C_DEFAULT;
              params[i].type   = SQL_NULL_DATA;
              params[i].length = SQL_NULL_DATA;
          }
          else if (value->IsInt32()) 
          {
              int64_t  *number = new int64_t(value->IntegerValue());
              params[i].c_type = SQL_C_LONG;
              params[i].type   = SQL_INTEGER;
              params[i].buffer = number; 
          }
          else if (value->IsNumber()) 
          {
              double   *number = new double(value->NumberValue());
              params[i].c_type = SQL_C_DOUBLE;
              params[i].type   = SQL_DECIMAL;
              params[i].buffer = number; 
          }
          else if (value->IsBoolean()) 
          {
              bool *boolean    = new bool(value->BooleanValue());
              params[i].c_type = SQL_C_BIT;
              params[i].type   = SQL_BIT;
              params[i].buffer = boolean;
          }
      }
  }
  else 
  {
      if ( !args[1]->IsFunction() )
      {
           return ThrowException(Exception::TypeError(
                      String::New("Argument 1 must be a Function"))
           );
      }

      cb = Local<Function>::Cast(args[1]);

      prep_req->paramCount = 0;
  }

  prep_req->sql = (char *) malloc(sql.length() +1);
  prep_req->catalog = NULL;
  prep_req->schema = NULL;
  prep_req->table = NULL;
  prep_req->type = NULL;
  prep_req->column = NULL;
  prep_req->cb = Persistent<Function>::New(cb);
  
  strcpy(prep_req->sql, *sql);
  
  prep_req->dbo = dbo;

  eio_custom(EIO_Query, EIO_PRI_DEFAULT, EIO_AfterQuery, prep_req);

  ev_ref(EV_DEFAULT_UC);
  dbo->Ref();
  scope.Close(Undefined());
  return Undefined();
}