Graph deep clone with SQL or javascript function - orientdb

Is there a SQL way to achieve OrientDB deep cloning?
Or otherwise is there a javascript server function (in orientdb studio) approach that can achieve it?

I tried with this little graph
and I used this server side javascript function
var g=orient.getGraph();
var myedge=g.command("sql","select #class as myclass,out,in from e");
for(i=0;i<myedge.length;i++){
var myEdgeClass=myedge[i].getProperty("myclass");
var VertexOutId= myedge[i].getProperty("out").getId();
var VertexInId= myedge[i].getProperty("in").getId();
var VertexOut=g.command("sql","select #class as myclass,#this.toJSON('fetchPlan:in_*:-2 out_*:-2') as json from " + VertexOutId);
var query="insert into " + VertexOut[0].getProperty("myclass") + " content"+VertexOut[0].getProperty("json");
var copyVertexOut=g.command("sql",query);
g.commit();
var VertexIn=g.command("sql","select #class as myclass,#this.toJSON('fetchPlan:in_*:-2 out_*:-2') as json from " + VertexInId);
query="insert into " + VertexIn[0].getProperty("myclass") + " content"+VertexIn[0].getProperty("json");
var copyVertexIn=g.command("sql",query);
g.commit();
query="create edge " + myEdgeClass + " from " + copyVertexOut.getId() + " to " + copyVertexIn.getId();
g.command("sql",query);
}
and I got
I hope it could be a help and a starting point for you.

Related

JPQL. JPA Query. How to get size of named parameter collection

I'm trying to define custom method in repository interface
public interface RequestRepository extends JpaRepository<Request, Long> {
#Query("SELECT r FROM Request r " +
"LEFT JOIN FETCH r.pathParams pp " +
"WHERE r.responseCode = :code " +
"AND r.requestMethod = :method " +
"AND r.requestPath = :path " +
"AND r.requestBody = :body " +
"AND r.apiDetails = :apidetails " +
"AND (pp IN :pathparams OR r.pathParams IS EMPTY) " +
"AND SIZE(r.pathParams) = :pathparamssize "
)
Optional<Request> findByDetails(
#Param("code") String code,
#Param("method") RequestMethod method,
#Param("path") String path,
#Param("body") RequestBody body,
#Param("apidetails") ApiDetails apidetails,
#Param("pathparams") Set<PathParam> pathparams,
#Param("pathparamssize") Integer pathparamssize
);
}
It works, but I believe it can be done in better way
As you can see I declared redundant parameter "pathparamssize" (IMO)
I tried to do that like "AND SIZE(r.pathParams) = SIZE(:pathparams) " but it doesn't want to work with "SIZE(:pathparams)"
can you please advise something?
many thanks in advance

Making raw SQL safe in Entity Framework

var retval = db.TestTable.SqlQuery("SELECT * FROM dbo.TestTable WHERE " + aColumn + " = '" + passedInValue + "'");
// normally when using parameters I would do something like this:
var valueParam = SqlParameter("aValue", passedInValues);
var retval = db.TestTable.SqlQuery("SELECT * FROM dbo.TestTable WHERE Column1 = #aValue", valueParam);
// NOTE: I would not do this at all. I know to use LINQ. But for this question, I'm concentrating on the issue of passing variables to a raw sql string.
But since both the column and value are "parameters" in:
var retval = db.TestTable.SqlQuery("SELECT * FROM dbo.TestTable WHERE " + aColumn + " = '" + passedInValue + "'");
, is there to prevent sql injection for both?
First: whilelist aColumn: this has to be added via string concatenation but you know what columns are in your database (or you can check using schema views).
Second: In entity framework – as you show – you can use parameters for values in the query. However, rather than creating SqlParameter instances you can pass the values and use #p0, #p1, ….
Right way to prevent SQL injection is to use SqlParameter and SqlQuery<T>:
var parameter = new SqlParameter("#title", value);
var result = context.Database.SqlQuery<Book>("SELECT * FROM Books WHERE Title LIKE #title", parameter);
http://ignoringthevoices.blogspot.ru/2013/07/sql-injection-with-entity-framework-5.html

How to create a derby user

I tried to set the DB schema name by schema.xml but it caused a schema name duplication in the generated SQL statement for ID generators. (Duplicate schema name in sequece generation)
I read the schema is defined by the passed user at connection time. Now I would like to set the schema by this way.
But I don't know how can I create a new Derby user and link it with the desired schema. Can somebody help me?
Environment: NetBeans, Glassfish, Derby
I have found this:
CALL SYSCS_UTIL.SYSCS_CREATE_USER('username', 'password')
But Derby answers:
Error code -1, SQL state 42Y03: 'SYSCS_UTIL.SYSCS_CREATE_USER' is not recognized as a function or procedure.
Why? I have connected to the db as the default admin user.
Or if I try to dispatch this command from a GUI tool, Derby says:
[Error Code: 0, SQL State: 42Y07] : Schema 'SYSCS_UTIL' does not exist
To Create user in Derby :
I am using Command Line Interface and I have already set my System environment variable to Derby.
Otherwise you can write these command into your CLI
java -jar %DERBY_HOME%\lib\derbyrun.jar ij
and hit Enter key to run ij tool, and you will see a prompt like this:
ij>
Now type the following command to create a user (replace sam by the desired username and sampass by the desired password):
CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.user.sam','sampass');
Now hit enter. This should give a message like this:
0 rows inserted/updated/deleted.
here is a solution (heavily commented):
String setProperty = "CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(";
String getProperty = "VALUES SYSCS_UTIL.SYSCS_GET_DATABASE_PROPERTY(";
String requireAuth = "'derby.connection.requireAuthentication'";
String sqlAuthorization = "'derby.database.sqlAuthorization'";
String defaultConnMode = "'derby.database.defaultConnectionMode'";
String fullAccessUsers = "'derby.database.fullAccessUsers'";
String readOnlyAccessUsers = "'derby.database.readOnlyAccessUsers'";
String provider = "'derby.authentication.provider'";
String propertiesOnly = "'derby.database.propertiesOnly'";
System.out.println("Turning on authentication and SQL authorization.");
Statement s = conn.createStatement();
// Set requireAuthentication
s.executeUpdate(setProperty + requireAuth + ", 'true')");
//CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.connection.requireAuthentication','true'
// Set sqlAuthorization
s.executeUpdate(setProperty + sqlAuthorization + ", 'true')");
//CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY('derby.database.sqlAuthentication','true'
// Retrieve and display property values
ResultSet rs = s.executeQuery(getProperty + requireAuth + ")");
rs.next();
System.out.println("Value of requireAuthentication is " + rs.getString(1));
rs = s.executeQuery(getProperty + sqlAuthorization + ")");
rs.next();
System.out.println("Value of sqlAuthorization is " + rs.getString(1));
// Set authentication scheme to Derby builtin
s.executeUpdate(setProperty + provider + ", 'BUILTIN')");
// Create some sample users
s.executeUpdate(setProperty + "'derby.user." + txtUname.getText() + "', '" + txtPw1.getText() + "')" );
// Define noAccess as default connection mode
s.executeUpdate(setProperty + defaultConnMode + ", 'noAccess')");
// Confirm default connection mode
rs = s.executeQuery(getProperty + defaultConnMode + ")");
rs.next();
System.out.println("Value of defaultConnectionMode is " + rs.getString(1));
// Define read-write users
s.executeUpdate(setProperty + fullAccessUsers + ", '" + txtUname.getText() + "')");
// Define read-only user
// s.executeUpdate(setProperty + readOnlyAccessUsers + ", 'guest')");
// Confirm full-access users
rs = s.executeQuery(getProperty + fullAccessUsers + ")");
rs.next();
System.out.println("Value of fullAccessUsers is " + rs.getString(1));
// Confirm read-only users
rs = s.executeQuery(getProperty + readOnlyAccessUsers + ")");
rs.next();
System.out.println("Value of readOnlyAccessUsers is " + rs.getString(1));
// We would set the following property to TRUE only when we were
// ready to deploy. Setting it to FALSE means that we can always
// override using system properties if we accidentally paint
// ourselves into a corner.
s.executeUpdate("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY(" + "'derby.database.propertiesOnly', 'false')");
s.close();
Let me know if that works (or not) for you.

Google maps downloadUrl does not return 200

My code is based on the example of google code:
https://developers.google.com/maps/articles/phpsqlinfo_v3
and was working fine.
I need to change a former 'gid' (Integer) field to 'id' (String) to get saved to the database and used to display a new labeled symbol on the map.
The strange thing is, that the url, that is build in the code to call the addrow.php file is OK. When I capture this string with alert(url), and I manually use this string, the new data is added to the database.
In my script, the call seems to fail (responseCode == 200 && data.length <=1), since no data is written to the database and the alert from the 'else-clause' is displayed as short pop-up.
Here's the code I use in my project (to save data from a form):
//save new marker to Postgis-database and add new markerwithlabel on the fly
function saveData(){
var gender = escape(document.getElementById("gender").value);
var hoehe = InZahl(document.getElementById("hoehe").value);
var breite = InZahl(document.getElementById("breite").value);
var id = escape(document.getElementById("id").value);
var vital = document.getElementById("vital").value;
var typ = document.getElementById("typ").value;
var ein_mehr = document.getElementById("ein_mehr").value;
var st_durchm = document.getElementById("st_durchm").value;
var frucht = document.getElementById("frucht").value;
var anmerk = document.getElementById("anmerk").value;
var latlng = marker.getPosition();
var url = "./mapdata/addrow.php?gender=" + gender +
"&hoehe=" + hoehe + "&lat=" + latlng.lat() + "&lng=" + latlng.lng() +
"&breite=" + breite + "&id=" + id + "&typ=" + typ + "&ein_mehr=" +ein_mehr + "&st_durchm=" + st_durchm +
"&frucht=" + frucht +
"&vital=" + vital + "&anmerk=" + anmerk;
downloadUrl(url, function (data, responseCode) {
if (responseCode == 200 && data.length <=1) {
infowindow.close();
marker.setDraggable(false);
marker.setIcon('./images/mm_purple.png');
marker.labelContent = id;
marker.setMap(map);
downloadUrl("./mapdata/getxml_get_last.php", function (data1) {
var xml = parseXml(data1);
var ms = xml.documentElement.getElementsByTagName("m");
var gid = ms[0].getAttribute("gid");
var html_n = "<div id='InfoWindow'><p style='font-weight:bold;'>" + id + "</p> \n\<p>Höhe:" + hoehe + " Breite: "+ breite +
"<br />\n\Typ: "+typ+" Stämme: "+ein_mehr+" St-Durchm: "+ st_durchm + "<br />\n\Vitalität: "+vital+" Fruchtbehang: "+frucht+
"<p/>\n\<p style='text-align:right;'><a href='sm_juniperus.php?operation=ssearch&ResetFilter=0&SearchField=gid&FilterType=%3D&FilterText="+ gid +
"' target='_blank'> Daten editieren </a></p></div>";
infowindow.setContent(html_n);
bindInfoWindow(marker, map, infowindow, html_n);
(function(i, marker, gid) {
var origIcon = marker.getIcon();
new LongPress(marker, 1000);
google.maps.event.addListener(marker, 'longpress', function(e) {
marker.setDraggable(true);
marker.setIcon(mmcross);
});
google.maps.event.addListener(marker, 'dragend', function(){
updatePosition(marker, gid);
marker.setIcon(origIcon);
});
})(i,marker,gid);
//add new marker to markerCluster-Array and to markerArray
markerCluster.addMarker(marker,false);
markerArray.push(marker);
i++;
}); // End add new marker
}
else {
alert("Your data couldn't be saved!");
}
}); // End downloadUrl
}; // END saveData()
As I said, my code worked fine, but after 3 evenings passed to solve this, I thought it would be time to ask for help.
If anybody has an idea, where the mistake lies, I would apreciate any hint.
Just to confirm, you're aware that you by doing
if (responseCode == 200 && data.length <=1) {
you are saying 'if the request is successful and the data it returns is only one character or below in length'? I am unsure if this is intended or not, because this way the code inside the if statement is only ran if the response is successful but contains only 1 or 0 characters.

DbCommand , Must Declare a variable error

This is my code. I have added the db parameter too but it still shows me error (on execution). Must declare a scalar variable
DbCommand command;
StringBuilder query = new StringBuilder(
#"SELECT isnull(UpsellService_OID,'') UpsellService_OID," + Environment.NewLine +
" isnull(ServiceName,'') ServiceName," + Environment.NewLine +
" isnull(ServiceDescription,'') ServiceDescription," + Environment.NewLine +
" isnull(Create_By,'') Create_By," + Environment.NewLine +
" isnull(Create_Date,'') Create_Date," + Environment.NewLine +
" isnull(Modify_By,'') Modify_By," + Environment.NewLine +
" isnull(Modify_Date,'') Modify_Date," + Environment.NewLine +
" isnull(Active_f,'') Active_f" + Environment.NewLine +
"FROM TRGPAYROLL.ZONG.UPSELLSERVICES " + Environment.NewLine +
"WHERE 1 = 1");
if (!string.IsNullOrEmpty(idObject.ServiceName))
{
query.Append(" AND ServiceName like '%' #ServiceName '%'");
}
command = db.GetSqlStringCommand(query.ToString());
if (!string.IsNullOrEmpty(idObject.ServiceName))
{
db.AddInParameter(command, "ServiceName", DbType.String, idObject.ServiceName);
}
return command;
I would rewrite the last part of your code in this way
if (!string.IsNullOrEmpty(idObject.ServiceName))
{
query.Append(" AND ServiceName like #ServiceName");
}
command = db.GetSqlStringCommand(query.ToString());
if (!string.IsNullOrEmpty(idObject.ServiceName))
{
db.AddInParameter(command, "#ServiceName", DbType.String, "%" + idObject.ServiceName + "%");
}
The wildcard are added directly to the value of the parameter, while the placeholder of the parameter should be free from any string concatenations. However there are many details missing to be sure of the correctness of this answer. In particular Ican only assume the inner workings of the methods GetSqlStringCommand and AddInParameter
#ServiceName variable is not declared in your SQL statement. Append to beggining of it something like
DECLARE #ServiceName AS nchar(32)
SET #ServiceName = ....