CodeIgniter dbutil & db point to different database (How to backup current database) - database

I have a trouble with dbutil and db.
Below is my code (a constructor of my model):
public function __construct(){
// I save my database configuration in CI session
$this->load->library('session');
$config = $this->session->userdata("db_config");
if($config){ // $config is now equal contains of my database configuration
$this->db = $this->load->database($config, TRUE);
}else{
$this->db = $this->load->database();
}
$this->load->dbutil();
echo '<pre>'.print_r($this->db, TRUE).'</pre>';
echo '<pre>'.print_r($this->dbutil, TRUE).'</pre>';
}
I found that $this->db and $this->dbutil point to different databases.
$this->db point to database config from session:
....
[username] => root
[password] => toor
[hostname] => localhost
[database] => coba
....
While $this->dbutil point to database config from my configuration file (application/config/database.php):
....
[username] => root
[password] => toor
[hostname] => localhost
[database] => module_devel
....
This is not expected, since I expect both of $this->db and $this->dbutil point to the same database
I've also check PHP: CodeIgniter; Managing two db connections; variable database parameters. But, for me the solution doesn't work at all.
So, anyone can discover what's wrong here?

It seems that it is a bug of CodeIgniter. But, dbutil is not the only we can use.
There are many alternatives to emulate what dbutil can do.
In my case, I want to generate a "create table" script. I end up using
$query = $this->db->query("SHOW CREATE TABLE `$table_name`");
And to generate SQL insert script, I do manual select, loop through the records and produce the script.
Hope this can help anyone else with similar problem

Related

How to whitelist ip address to access oracle database

I am new to oracle database. I work on 12c version oracle database which is hosted in linux platform. I have to whitelist a list of ip addresses to access the oracle database.
Example: Below are the server details and i need to add my ipaddress to connect to the database
(PROTOCOL = TCP)(HOST = 192.168.56.122) (PORT = 1521)
kishan 192.108.10.132 xyz#gmail.com
I have gone through these documents but it was not quite helpful. Any help would be much appreciated!
https://docs.oracle.com/en/cloud/paas/casb-cloud/palug/putting-ip-addresses-blacklists-or-whitelists.html#GUID-17060E3D-D8B6-41F1-AAEB-9CC3F4D7B670
https://docs.oracle.com/en/cloud/paas/exadata-express-cloud/csdbp/configure-ip-whitelist-policy.html
Looks like you're looking for ACL (Access Control List). Here's an example:
Create ACL:
BEGIN
DBMS_NETWORK_ACL_ADMIN.create_acl (
acl => 'kishan.xml',
description => 'HTTP Access',
principal => 'KISHAN', -- user in your database
is_grant => TRUE,
privilege => 'connect',
start_date => NULL,
end_date => NULL);
END;
/
Assign ACL:
BEGIN
DBMS_NETWORK_ACL_ADMIN.assign_acl (acl => 'kishan.xml',
HOST => '192.108.10.132',
lower_port => NULL,
upper_port => NULL);
END;
/
Add privilege
BEGIN
-- TRAFOGLED
DBMS_NETWORK_ACL_ADMIN.add_privilege (acl => 'kishan.xml',
principal => 'KISHAN',
is_grant => TRUE,
privilege => 'connect',
start_date => NULL,
end_date => NULL);
DBMS_NETWORK_ACL_ADMIN.add_privilege (acl => 'kishan.xml',
principal => 'KISHAN',
is_grant => TRUE,
privilege => 'resolve',
start_date => NULL,
end_date => NULL);
END;
/
COMMIT;
After you've done all that, user KISHAN should have access to 192.108.10.132. If there are other users that should gain the same access, just add them into the "add privilege" script.
ACLs as described by #Littlefoot control access from within the database to external resources (e.g. a PL/SQL stored procedure accessing a web service or e-mail server). If you're talking about whitelisting database clients, connecting to the DB from other hosts, there are a couple of options, but be careful not to work yourself into a corner in terms of administrative overhead. It is very important to consider what is the actual problem you are trying to solve.
You can use
the host server's local firewall (e.g. iptables, firewall1, etc.) to restrict access to port 1521 (or whatever port you're using);
the TCP.INVITED_NODES parameter in sqlnet.ora (see here: https://docs.oracle.com/en/database/oracle/oracle-database/19/netrf/parameters-for-the-sqlnet.ora.html#GUID-897ABB80-64FE-4F13-9F8C-99361BB4465C);
or use Oracle Connection Manager if you have an Enterprise Edition database.
In general I wouldn't restrict to anything more narrow than a subnet, though. The reason for that is that there isn't any good way to do it more precisely: IP addresses tend to change frequently with DHCP, which could result in a user being unintentionally locked out, and they can be easily spoofed by bad actors. Tracking each individual IP is an administrative nightmare, too.
See these articles I wrote up last year for more detail and some of the important questions to consider:
https://pmdba.wordpress.com/2020/02/18/how-to-limit-a-user-connection-to-a-specific-ip-address/
https://pmdba.files.wordpress.com/2013/03/deploying-an-oracle-11gr2-connection-manager.pdf

Yii2: Connect to Oracle database

I need to connect a Yii2 model to an Oracle database but it is not working despite reading several answers on this topic.
The Oracle login credentials that I use to manually log in are similar to:
host: hosturl.abc.com
port: 1521
SID: sidname
user: username
password: passABC
In the manual login process, I then need to select the appropriate Schema, after which I can see all tables.
I am not clear how to include these details in the oci connection. Here is what I have done without success:
'db2' => [
'class' => 'yii\db\Connection',
'dsn' => 'oci:dbname=//hosturl.abc.com:1521/sidname;charset=UFT-8',
'username' => 'username',
'password' => 'passABC'
],
I get an error "The table does not exist: TableName" however, I get this message even if I supply completely random details ie wrong username, wrong host, wrong password etc)
I am not clear why I cannot connect. Perhaps the Oracle database is rejecting all queries? Do I need to include the SID in the connection credentials?
Any help appreciated
UPDATE
I think there must be a more general problem with my installation. I am trying a raw connection as follows:
$conn = oci_connect("username", "passABC", "//hosturl.abc.com/sidname");
if (!$conn) {
print "There is a problem";
} else {
print "Connected to Oracle!";
}
This returns the following error:
Call to undefined function oci_connect()
Any suggestions? This looks like a problem with my php setup??
SOLVED!
1) oci_connect not working: SOLVED
Please see this post for more details How do I connect PHP 7.x to Oracle database on RedHat / CentOS?. This fix was required for Yii2 to connect to Oracle.
2) Yii2 db credentials for an Oracle database
/common/config/main-local:
'db' = [
'class' => 'yii\db\Connection',
'dsn' => 'oci:dbname=//hosturl:1521/SID;charset=UTF8',
'username' => 'dbusername',
'password' => 'dbpassword',
]
I tried a number of Yii2 oci8 extensions but none of them worked for me. Instead, the fix (1) for the oci_connect worked and no additional Yii2 drivers were required. I was able to use the standard 'yii\db\Connection' class.
3) Database Schema
Within the Oracle database we have a number of schemas and I wasn't sure how to query a specific table within a particular schema. Ultimately the solution was simple: Within each model, prepend the schema name to the table name. For example:
class myTable extends ActiveRecord
{
public static function tableName()
{
return 'schemaName.myTable';
}

IdentityServer4 Sample with ASP Identity with real SQL Server

I have been struggling to get the final SAMPLE (ASP.Net, EF Core, SQL) to work against a real SQL Server. Every sample I can find does not use real SQL they always opt for in-memory data store
I changed the connection string
"Data Source=.;Initial Catalog=IS4;Integrated Security=True;"
and ran
dotnet ef database update -c ApplicationDbContext
This created me a SQL database with 25 tables.
I tweaked Startup.cs to change
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(connectionString));
and b.UseSqlite to b.UseSqlServer
.AddConfigurationStore(options =>
{
options.ConfigureDbContext = b =>
b.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
})
// this adds the operational data from DB (codes, tokens, consents)
.AddOperationalStore(options =>
{
options.ConfigureDbContext = b =>
b.UseSqlServer(connectionString,
sql => sql.MigrationsAssembly(migrationsAssembly));
// this enables automatic token cleanup. this is optional.
options.EnableTokenCleanup = true;
// options.TokenCleanupInterval = 15;
});
I ran the server with "/seed" on the command line but the Seed functionality doesn't work
First it complains CLIENT can't have a NULL ID when it calls SaveChanges(). If I change the code to add the ID
if (!context.Clients.Any())
{
Console.WriteLine("Clients being populated");
int i = 1;
foreach (var client in Config.GetClients().ToList())
{
var x = client.ToEntity();
x.Id = i++;
context.Clients.Add(x);
}
context.SaveChanges();
}
else
{
Console.WriteLine("Clients already populated");
}
I then get
"Cannot insert the value NULL into column 'Id', table 'IS4.dbo.ClientGrantTypes".
When I watch the video's it says it can be migrated from SQLite to full SQL simply by changing the connection string which is obviously not true, given all the other changes I have done, so I must be doing (or missing) something else.
Any thoughts?
Could it be that all the tables with an "Id INT" column should all be IDENTITY columns and they are not!
I checked the migrations code and it has
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "ApiResources",
columns: table => new
{
Id = table.Column<int>(nullable: false)
.Annotation("Sqlite:Autoincrement", true),
Description = table.Column<string>(maxLength: 1000, nullable: true),
DisplayName = table.Column<string>(maxLength: 200, nullable: true),
I am guessing
.Annotation("Sqlite:Autoincrement", true),
doesn't work with full SQL and therefore all the tables need identity properties setting.
Interestingly if you run the other template to add the AdminUI
dotnet new is4admin
It seems to add a couple of SQL scripts
CREATE TABLE "Clients" (
"Id" INTEGER NOT NULL CONSTRAINT "PK_Clients" PRIMARY KEY AUTOINCREMENT,
"AbsoluteRefreshTokenLifetime" INTEGER NOT NULL,
"AccessTokenLifetime" INTEGER NOT NULL,
which does make them identity columns.
I was faced with this issue today and did a couple of searches online and stumbled upon this https://entityframeworkcore.com/knowledge-base/46587067/ef-core---do-sqlserver-migrations-apply-to-sqlite-
The link pointed out to switch the annotation portion in the migration class UP method after
Id = table.Column(nullable: false)
from
.Annotation("Sqlite:Autoincrement", true);
to
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn)
And you will need to import
using Microsoft.EntityFrameworkCore.Metadata;
Then you build, and the migration will be successful.
To resolve this particular issue I used SSMS.
right click on table
select script to drop and create
add IDENTITY after the NOT NULL
Execute
However you are correct, it is using sqlite annotations in the sql file and in the migrations.
To fully resolve this issue, you need to create an implementation of all 3 necessary database contexts: identity, persisted grant, and configuration.
That requires an implementation of design time factories for each of those contexts as well.
Then you can run add-migration in the package manager console for each of those contexts, and then run update database, or run the application with the migrate function when seeding.
So to recap:
Create implementations for the 3 db contexts
Create Design time factory implementations for those db contexts
Add the migrations
Update the database with those migrations

Column "" declared twice in table "status" in Propel 2

I'm trying to reverse generate a schema from a MSSQL database using Propel 2. I've set up my YAML configuration file as usual:
dbname:
adapter: mssql
classname: Propel\Runtime\Connection\ConnectionWrapper
dsn: "dblib:host=123.456.789.012;dbname=dbname"
user: username
password: password
attributes:
When I run the command propel reverse 'dbname' I receive the error:
[Propel\Generator\Exception\EngineException]
Column "" declared twice in table "Status"
Which is obviously thrown here:
https://github.com/propelorm/Propel2/blob/master/src/Propel/Generator/Model/Table.php#L499
#r499
Why does Propel attempt to add 'empty' columns? My SQL server management studio does not display empty columns at all when I look at the design of the DB table Status, it only displays the two columns it contains (uid and name).
Edit:
So I went digging into the code of Propel, and it seems to go wrong here:
https://github.com/propelorm/Propel2/blob/62859fd0ed3520b7d7afbbdeac113edaf160982b/src/Propel/Generator/Reverse/MssqlSchemaParser.php#L124
protected function addColumns(Table $table)
{
$dataFetcher = $this->dbh->query("sp_columns '" . $table->getName() . "'");
foreach ($dataFetcher as $row) {
$name = $this->cleanDelimitedIdentifiers($row['COLUMN_NAME']);
$table->getName() correctly returns the right table name. When I print dataFetcher it's a PDO object. However:
$row gives the following array:
Array(
[0] => My DBname
[1] => My DBprefix
[2] => Status
[3] => uid
[4] => 4
[5] => int identity
etc. no string indices hence COLUMN_NAME is empty.
(Posted on behalf of the OP):
This is a bug in the Propel MSSQL schema parser: https://github.com/propelorm/Propel2/issues/863.

Returning MSSQL data using plperl function in PostgreSQL

I have a PostgreSQL database in use for a complex php web site (And VB.Net/C# management applications) which require access to execute stored procedures on a Microsoft SQL Server 2008 database. The method chosen to perform this interaction is to use plperl functions within the PostgreSQL database to wrap access to the MSSQL stored procedures.
We are using the perl DBI module to handle the data retrieval from MSSQL database.
I am a neophyte when it comes to perl in general and specifically when using it with PostgreSQL. I have created the function shown below to return a set of composite type
CREATE TYPE "public"."permissions_return" AS (
"rolename" TEXT,
"roledescription" TEXT,
"permissionname" TEXT,
"permissiondescription" TEXT
);
The stored proc called from within the function works fine and returns data when run through a slightly different perl script run from the command-line, or directly from the MSSQL Server. I have not been able to figure out how to return data from my function when using:
SELECT * FROM fn_perltest(153);
The result is always an empty set.
CREATE FUNCTION fn_perltest(integer) RETURNS SETOF permissions_return AS $$
use strict;
use DBI;
my $data_source = q/dbi:ODBC:Production/;
my $user = q/afunkyusername/;
my $password = q/afunkierpassword/;
my $dbh = DBI->connect($data_source, $user, $password);
my $sth = $dbh->prepare(q/up_DCORsel_getUserPermissionByUserID $1 ;/);
$sth->execute();
while ( defined ( my $row = $sth->fetchrow_array() )) {
return next ({
rolename => $row->{RoleName},
roledescription => $row->{RoleDescription},
permissionname => $row->{PermissionName},
permissiondescription => $row->{PermissionDescription}
});
}
return;
$$ LANGUAGE 'plperlu'
If this helps, Postgres is running on a Fedora 13 server. Access to MSSQL Server is configured using unixODBC with the freetds driver. Access to the MSSQL server has been tested and works fine using the isql command-line tool and a simple perl script.
Any ideas would be greatly appreciated. I'm concerned I may run out of hair to pull out.
Regards
Shane
This doesn't answer your question directly, but I have used dblink when attempting to have one database query data in another database. It seemed to work well. Obvious plperlu has a lot more power than dblink, but I don't have any experience with it (just perl and postgresql :-)
dblink can be found in postgresql's contrib directory.

Resources