Postgres PGSimpleDataSource changing database name - postgresql

This is what I am trying, I want to connect to a default admin database, create a new database and immediately switch to it.
Below is my pseudo-code:
// Create a new datasource
dataSource = PGSimpleDataSource()
dataSource.setURL("jdbc:postgresql://mydbserver:5432/admin")
dataSource.setUser("test")
dataSource.setPassword("testing")
// get connection to admin db and create a new database named 'mynewdb'
connection = dataSource.getConnection()
cs = connection.createStatement()
cs.executeUpdate("create database mynewdb")
cs.close()
connection.close()
// switch to the newly created database using the **same datasource**
dataSource.setDatabaseName(mynewdb)
connection_to_new_db = dataSource.getConnection()
ps = connection_to_new_db.preparedStatement()
....start doing transactions on the newly created database...
....start doing transactions on the newly created database...
Above code seems to work fine.
Questions:
is it legal to change the database name on the fly on an existing datasource? Are there any repercussions?
is this the right way to accomplish what I am trying or is there a better way?

Related

Add PostgreSQL databaseas data source for WinForms DataGridView

I've successfully connected to a PostgreSQL database by manually coding it (create connection string for IP address, port, credentials and database name, create the NpgsqlConnection object, and open the connection).
Now I need to add that database as a Data Source for a DataGridView in a WinForms project. I ran across Devart's dotConnection for PostgreSQL and downloaded the Express version. They have a documentation page, but for the life of me I can't figure out how to add the database as a datasource (I also reached out to their support email three days ago, but they've never responded.)
When I click Add New Data Source in the Data Sources tab and the Data Source Configuration Wizard opens, I'm not sure if I should select Database or Object. In any case, I'm not seeing how to add the PostgreSQL database connection information as a datasource through the wizard.
I believe the best way to do that is not to use the wizards, they hide code in .Designer.cs and .resx files and make maintenance difficult.
I recommend you do something like this programmatically:
DataGridView1.DataSource = GetData("Your sql");
public DataTable GetData(string selectSql)
{
try
{
DataSet ds = new DataSet();
string connstring = String.Format("Your conn string");
NpgsqlConnection conn = new NpgsqlConnection(connstring);
conn.Open();
NpgsqlDataAdapter da = new NpgsqlDataAdapter(selectSql, conn);
da.Fill(ds);
return ds.Tables[0];
}
finally
{
conn.Close();
}
}

EF Core - create database programmatically

What's the best approach to create a database in EF core programmatically and then run the migrations to make sure the new database has all database objects?
We're building a SaaS based application where subscribers can signup on the website themselves and when they signup providing correct payment details, the application needs to create a new database (in SQL Azure) for the subscriber automatically and execute all migrations on the new database.
I have looked at this question here:
auto create database in Entity Framework Core
It does not give details on the following:
1) how to specify the name of the new database
2) create a new database login
3) add that new database login to the database as a user with dbo permissions
Create an Azure SQL Database Basic tier (for example, it cost $5 a month, you can also create a free one available for a year) with all the objects needed on the database, which you can copy asynchronously with a statement like below or using PowerShell.
CREATE DATABASE db_copy
AS COPY OF ozabzw7545.db_original ( SERVICE_OBJECTIVE = 'P2' );
You can then monitor when the copy finishes with below statement:
Select
[sys].[databases].[name],
[sys].[databases].[state_desc],
[sys].[dm_database_copies].[start_date],
[sys].[dm_database_copies].[modify_date],
[sys].[dm_database_copies].[percent_complete],
[sys].[dm_database_copies].[error_code],
[sys].[dm_database_copies].[error_desc],
[sys].[dm_database_copies].[error_severity],
[sys].[dm_database_copies].[error_state]
From
[sys].[databases]
Left
Outer
Join
[sys].[dm_database_copies]
On
[sys].[databases].[database_id] = [sys].[dm_database_copies].[database_id]
Where
[sys].[databases].[name] = 'db_copy'

Check if database with specified name exists or not

As you may know that whenever we set a new database inside "sails-orientdb adapter" configurations it creates database, now on the creation time of the database of course database will be created if there is no database inside orientdb with this name, now I want to create vertices related to a class you can say those vertices are defaults of my application, whenever new database will be created those defaults will also be created, but when database already exists those defaults will also be skipped.
Now, is there any function like exists() available inside Waterline or Oriento which can check that database with the specified name inside configurations exists or not inside orientdb and return true or false?
There is not a function .exists() but Oriento has a function named .list() which will list all DBs and allows checking if a particular DB is present. To do this from Sails-OrientDB you can use the custom method .getServer() as follows:
// Assume a model named "Post"
Post.getServer()
.list()
.then(function (dbs) {
var dbExists = _.find(dbs, function(db) {
return db.name === 'myDatabaseName';
});
console.log('myDatabaseName exists:', dbExists);
});
This is the logic that Sails-OrientDB uses to determine if the DB exists before creating it: https://github.com/appscot/sails-orientdb/blob/master/lib/connection.js#L604-L608

Model is not reading from my Database (Entitity Framework)

I created simple MVC application with a database.
First I created a database, initialized the database, then I created a model from the database and the application worked..
Then I decide to load database with totaly different values (but the definitons of tables/fields stayed the same)..
After reloading the database my application does not shows any data from my DB. Using debugger I saw that my application cannot get any data from the table.
Worse - I noticed that additional to my database TestDB, the database explorer is showing TestDB.mdf1 database, with the same definitions as testDB.mdf but table is empty...
Here is the code:
public ActionResult ShowQuestions()
{
TestDBEntities _db = new TestDBEntities(); // this is the database
ObjectSet<question> all_quest = _db.questions ; // this is the table
foreach (var x in all_quest)
{
..... // this part was never executed
}
return View(q_list);
}
Any ideas what I am doing wrong?
1- check the connection string in your MVC application (web.config). This will tell you which database is being used. Then go to this database and check if you have data in your tables.
If it's the wrong database, just amend the connection string.
2- If it's the correct database, but without data, just add data.
It may have been recreated by your ORM (who knows?).
3- What is the error you are getting? Or are you getting any error?

EF Code First Existing database

Using EF 4.1 Code first I wanted to stop EF creating database from Models. As I understand if you pass Connectionstring name it will use existing database from that connection string. However if the database does not exists then it will create database will all the tables form the model.
<connectionStrings>
<add name="DiaryContext" connectionString="Data Source=.;Initial Catalog=Diary;Integrated Security=SSPI;" providerName="System.Data.SqlClient"/>
public MyDiaryContext() :
base("name=DiaryContext")
{
this.Configuration.LazyLoadingEnabled = true;
this.Configuration.ProxyCreationEnabled = false;
}
In the above example its behaving as follows:
(1) if database does not exists then it will create the database with all the tables etc.
(2) if the database exists and it has no tables then it will not create new tables
(3) if I add new model the EF code then it will not create the new table in the database.
I am happy with 2 and 3 but in case of (1) if database does not exists then I wanted it to throw the exception instead of creating the db and tables.
In my case the database is being managed by DBA and I dont have total control over this.
Does anyone have any idea how to achive this?
Many thanks,
When you use EF Code first you need to set a DB Initializer I for example do this in the constructor of my DataContext
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<WebContext>());
There are a few default implmentations like DropCreateDatabaseIfModelChanges and DropCreateDatabaseAlways you can use. If however you don't wont any DB or tables generate just make sure that no Initializer is being set or inherited from and you can use the model against an existing db. Good article by scot gu