Do I need to "close" a connection in SQLite.swift? - sqlite.swift

Not sure about whether I should and how to close a Connection in SQLite.swift. Will it cause thread/memory leak?

Normally the database is closed when the Connection variable is out of its using scope and reclaimed by the trash-collecting system (in the deinit function). But sometimes it is one of your class's attributes, so you might want to close it manually in the middle of some functions. Hence this code works:
sqlite3_close(db.handle)
where db has the type of Connection. You can then override the database file or delete it, no warnings will be raised.
Anyways, I highly recommend you design your code in a cautious way to let the system frees the handle.

Although SQLite does close connections automatically. To avoid potential race conditions from dangling threads. I add this to the end of my generic Swift query function for completeness.
if sqlite3_close(db) != SQLITE_OK {
print("error closing database")
}
Where
var db: OpaquePointer?
var databaseFullPath: String = "" /// Location database.
if sqlite3_open(databaseFullPath, &db) != SQLITE_OK {
print("error opening database")
}
Additional Information:
sqlite3_close() documentation.

Sqlite connection will close automatically if u don't do it manually.
for e.g:
try {
conn.close();
}
catch (Exception ex) {
System.out.println ("Error");
return false;
}

Related

Should database connections be opened and closed in every CRUD method?

I am using GORM ORM for Postgres access in a Go application.
I have got 4 functions, Create, Update, Delete, and Read in a database repository.
In each of these functions, I open a database connection, perform a CRUD operation and then close the connection just after the operation is performed as you will see here and here and in the code snippet below, using GORM
func (e *Example) Create(m *model.Example) (*model.Example, error) {
// open a database session
dbSession, err := e.OpenDB() //gorm.Open("postgres", connStr)
if err != nil {
log.Log(err)
return nil, err
}
// close database connection after operation is completed
defer dbSession.Close()
// create item
db := dbSession.Create(m)
if db.Error != nil {
return nil, db.Error
}
return m, nil
}
Is that the correct practice or should one database connection be shared in the whole application and let the ORM handle managing connections? as stated here?
You should reuse a DB connection as much as you can. Also gorm has a built-in connection pool, so, you don't need to manage the db handle. Simply share it amongst all goroutines and they can share the handle safely, allocating new connections as needed.

JsPlumb flowchart no self-connections

I have a problem where I'm more-or less using the jsPlumb flow-chart demo example but where there is only ever one drop target per window and there may be one or many drag targets. However I want to forbid self-connections so that a connection can be dragged from any window to any other window EXCEPT itself.
I was thinking that maybe you would use scopes but this would mean a different scope for each window which seems over the top. Does anyone have a tidy solution?
Thanks for the answers they pointed me in the right direction. In the end used "beforeDrop"
when binding the "connection" it was detaching the source endpoint of the window as well as the connection.
The final solution was:
instance.bind("beforeDrop", function (info) {
// console.log("before drop: " + info.sourceId + ", " + info.targetId);
if (info.sourceId === info.targetId) { //source and target ID's are same
console.log("source and target ID's are the same - self connections not allowed.")
return false;
} else {
return true;
}
});
from http://www.jsplumb.org/doc/connections.html#draganddrop
Preventing Loopback Connections
In vanilla jsPlumb only, you can instruct jsPlumb to prevent loopback connections without having to resort to a beforeDrop interceptor. You do this by setting allowLoopback:false on the parameters passed to the makeTarget method:
jsPlumb.makeTarget("foo", {
allowLoopback:false
});
Bind an event to get notified whenever new connection is created. After connection creation check whether source and target of connection are same, if so detach that connection to avoid self loop. Code:
jsPlumb.bind("jsPlumbConnection", function(ci) {
var s=ci.sourceId,c=ci.targetId;
if( s===c ){ //source and target ID's are same
jsPlumb.detach(ci.connection);
}
else{ // Keep connection if ID's are different (Do nothing)
// console.log(s+"->"+c);
}
});

Visual Basic - Check To See If Program Can Edit Registry [duplicate]

Does anybody know how I can programmatically check (using C#) whether my program will be able to read / write a particular registry key (specifically: "SOFTWARE\Microsoft\Windows\CurrentVersion\Run")?
I am asking because my program has the option to enable or disable the 'run at startup' behaviour. I want to disable this option if the current user is not allowed to make changes to the registry. Is this key always allowed to be written by the current user, or is there the possibility that it has been locked down? If the latter, how do I check this?
I have seen several conflicting ways of checking registry permissions - but basically I can't find a way to check a specific key before I try to read it. I would rather perform the check before accessing the key than trying to access it and receive an exception.
Any help is much appreciated.
Tom
The RegistryPermission class governs the security permissions around reg keys. To check if you may have write access to a permission you use it in the following manner:
RegistryPermission perm1 = new RegistryPermission(RegistryPermissionAccess.Write, #"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
You would then use the "Demand" method in a try/catch and return on failure (the raising of a security exception). On success you'd carry on and perform your update. Although this isn't quite what you want, a check on permissions before access, it is the accepted way of ensuring you have the permissions you need before you operate on the keys. In a fully structured manner this would equate to:
try
{
RegistryPermission perm1 = new RegistryPermission(RegistryPermissionAccess.Write, #"SOFTWARE\Microsoft\Windows\CurrentVersion\Run");
perm1.Demand();
}
catch (System.Security.SecurityException ex)
{
return;
}
//Do your reg updates here
EDIT: Thinking on what I mentioned in the comment, here are extension methods to the RegistryPermission class for permission checks:
using System.Security.Permissions;
using System.Security;
public static class RegistryExtensions
{
public static bool HavePermissionsOnKey(this RegistryPermission reg, RegistryPermissionAccess accessLevel, string key)
{
try
{
RegistryPermission r = new RegistryPermission(accessLevel, key);
r.Demand();
return true;
}
catch (SecurityException)
{
return false;
}
}
public static bool CanWriteKey(this RegistryPermission reg, string key)
{
try
{
RegistryPermission r = new RegistryPermission(RegistryPermissionAccess.Write, key);
r.Demand();
return true;
}
catch (SecurityException)
{
return false;
}
}
public static bool CanReadKey(this RegistryPermission reg, string key)
{
try
{
RegistryPermission r = new RegistryPermission(RegistryPermissionAccess.Read, key);
r.Demand();
return true;
}
catch (SecurityException)
{
return false;
}
}
}
One thing you should know about permissions is that they are volatile. That means you could do your security check on the registry key, attempt to add your value only if the check passes, and then still fail with an insufficient access exception because the permissions changed in between when you made the check and when you acted on the results. This is possible even if they are consecutive statements in your program.
Granted security permissions tend to be relatively stable, but the chance still exists. This means that you must have code to handle the security exception, and if you have to do that anyway there's not really any point in making the check in the first place. Instead, put your time into making your exception handler a little bit better.
That said, "boo" to any app that wants to run something at start-up. YAGNI.
I think you best bet is to just try to add your value to the key, and handle failure gracefully by informing the user they didn't have enough permissions to do that.
If you're writing some sort of administrative tool that is designed to always be run by an administrator, you should indicate that in the manifest. That way your app will elevate at startup (via UAC prompt).
Simplest option is to try and open the key with write access and see if you get it. Remember to close the key afterwards.
bool fWriteAccess;
try {
Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True).Close();
fWriteAccess = True;
} catch (SecurityException) {
fWriteAccess = False;
}
I'm not sure how to it with C#, but with Win32, you would use RegGetKeySecurity(). Maybe there's a C# wrapper? Otherwise, use P/Invoke.
Just try to open the registry key with WRITE permissions.
That said, what others have said is right: There is no way to tell if an operation is going to succeed unless you try it. Maybe someon deleted the Run key. Maybe the registry will exceed allocated memory. Maybe the disk failed.

CA2202 Warning from Code Analysis for OracleConnection disposal

We are getting the following warning from Code Analysis in Visual Studio 2010 and I'm wondering if this is a false positive that we can safely ignore or the code should be refactored to correctly dispose the object.
The relevant code:
public void MyFunction()
{
OracleConnection oraConnection = null;
OracleCommand oraCommand = null;
try
{
// Connect to the database
oraConnection = new OracleConnection(connectionString);
oraConnection.Open();
// Prepare and run the query
oraCommand = new OracleCommand(sqlQuery, oraConnection);
oraCommand.ExecuteNonQuery();
}
catch { throw; }
finally
{
// Perform a safe cleanup
if (oraCommand != null) { oraCommand.Dispose(); }
if (oraConnection != null)
{
oraConnection.Close();
oraConnection.Dispose();
}
}
}
The relevant error message:
Warning 18 CA2202 : Microsoft.Usage : Object 'oraConnection' can be disposed
more than once in method 'ClassName.MyFunction()'. To avoid generating a
System.ObjectDisposedException you should not call Dispose more than one
time on an object.
If you remove the line:
oraConnection.Close();
it should get rid of the warning, since closing and disposing a connection are essentially the same thing.
You might also want to replace your try/finally by a using statement.
Note that Microsoft's own guidelines say that IDisposable.Dispose should be implemented in such a way that it can safely be called multiple times. Which means that the CA2202 warning can safely be ignored, as noted in the comment by JoeM27 on the MSDN page for CA2202.

Unable to close JDBC resources!

We are running a websphere commerce site with an oracle DB and facing an issue where we are running out of db connections.
We are using a JDBCHelper singleton for getting the prepared statements and cosing the connections.
public static JDBCHelper getJDBCHelper() {
if (theObject == null){
theObject = new JDBCHelper();
}
return theObject;
}
public void closeResources(Connection con, PreparedStatement pstmt, ResultSet rs){
try{
if(rs!=null){ rs.close();}
}catch(SQLException e){
logger.info("Exception closing the resultset");
}try{
if(pstmt!=null) { pstmt.close(); }
}catch(SQLException e){
logger.info("Exception closing the preparedstatement");
}try{
if(con!=null){ con.close(); }
}catch(SQLException e){
logger.info("Exception closing the connection");
}
}
However when we try getting the connection using a prepStmt.getConnection() for passing to the close resources after execution it throws an sql exception. Any idea why? Does the connection get closed immediately after execution? And is there something wrong in our use of the singleton JDBCHelper?
EDIT
Part of the code which makes the prepared statement,executes and closes the connection
PreparedStatement pstmt = jdbcHelper.getPreparedStatement(query);
try{
//rest of the code
int brs = pstmt.executeUpdate();
}
finally{
try {
jdbcHelper.closeResources(pstmt.getConnection(),pstmt);
} catch (SQLException e1) {
logger.logp(Level.SEVERE,CLASS_NAME,methodName,"In the finally block - Could not close connection", e1);
}
}
Your connection will most likely come from a pool, and closing it actually will return the connection to the pool (under the covers). I think posting the code which gets the connection, uses it and closes it via JDBCHelper will be of more use.
Re. your singleton, I'm not sure why you're using this, since it doesn't appear to have anything to warrant it being a singleton. Check out Apache Commons DbUtils which does this sort of stuff and more besides.
This code seems to be written for single threaded operation only, as it's lacking any synchronisation code. The getJdbcHelper() method for instance is likely to create two JdbcHelpers. If I'm not mistaken there's even no guarantee that a second thread will see theObject, long after a primary thread has created it. Although they usually will, by virtue of the architecture the JVM runs on.
If you're running this inside a web server you're likely to be running into race issues, where two threads are modifying your connection at the same time. Unless you rolled your own connection pool or something.
Brian is right, use one of the freely available libraries that solve this (hard) problem for you.

Resources