My postgres is running locally on Mac on a port 5432
It has database on it named test, and this database has one table in it called test_table
I'm trying to connect to it using GO.
Imports:
"database/sql"
_ "github.com/lib/pq"
Main:
db, err := sql.Open("postgres", "postgres://user:#localhost:5432/test")
if err != nil {
log.Println(err)
}
defer db.Close()
if err2 := db.Ping(); err2 != nil {
fmt.Println("Failed to keep connection alive")
}
db.QueryRow("INSERT INTO test.test_table (name) VALUES (`something`)) RETURNING id").Scan(&id)
fmt.Println(id)
To test the connection I'm running Ping and also try to Insert one line into test_table. But it returns me:
Failed to keep connection alive
0
How can I fix the problem?
In situations like these, it pays to go through the following checklist:
can you connect to the server using the same arguments provided to the go server? I.e. can you run psql -U user -p 5432 -h localhost test ?
are you printing all errors? In the question, err2 should be printed, as it contains critical information about what's going on. Scan also returns an error that is not being saved to a variable or printed. If it were, you might have seen the syntax problem in your query.
can you you run the query in the SQL shell? (psql) If not, fix the query first before continuing.
Related
consider i have two database in mongoDB say db1 and db2 i want to change the password for both initially , do i need to logout db1 before changing db2 password ? or that is not required ? what's the best practice?
current sequence
conn, err := mongo.connect(ctx, connOpts)
//then update the db pass
cmd := bson.D{{"updateUser", dbUserName}, {"pwd", newPass}}
err = client.Database(db1).RunCommand(context.TODO(), command, opts).Decode(&result)
//then logout
err = client.Database(db1).RunCommand(context.TODO(), bson.D{{"logout", 1}}, opts).Decode(&result)
//repeat the same steps again for changing the db2 password
Am I following the right sequence ? whether connecting the db once is enough to do both operation ? is login and logout really required here ?
I'm using go mongo driver .
Really strange yet very common error. Relation "users" does not exist. I know what you are saying - that's been asked before! And it has, but work with me because I'm doing a bunch of checks and it still doesn't go through.
First, this is the migration:
CREATE TABLE users (
id serial PRIMARY KEY,
obfuscated_id VARCHAR(128) NOT NULL UNIQUE,
email VARCHAR(128) NOT NULL UNIQUE,
encrypted_password VARCHAR(128) NOT NULL,
created_at TIMESTAMP,
updated_at TIMESTAMP,
active BOOLEAN DEFAULT TRUE
);
And this is the command I'm using to run that migration:
migrate -path ./migrations -database postgres://myname:password#localhost:5432/five_three_one_development?sslmode=disable up
I've manually tested that the db exists:
psql
\c five_three_one_development
\dt
Schema | Name | Type | Owner
--------+-------------------+-------+----------
public | schema_migrations | table | myname
public | users | table | myname
I've manually altered the password on the table using /password and set it to password.
Here are the environment variables:
DB_NAME=five_three_one_development
DB_PASS=password
DB_USER=myname
And when I log those variables I get the same values back:
fmt.Printf("NAME:" + os.Getenv("DB_NAME"))
fmt.Printf("USER:" + os.Getenv("DB_USER"))
fmt.Printf("DB_PASS:" + os.Getenv("DB_PASS"))
I also perform an environment test at the top of my development server to check that the db is reachable.
func (c *ApplicationContext) PerformEnvChecks() {
err := c.Database.Ping()
if err != nil {
log.Fatalf("Database environment check failed: %s", err)
}
r, err := c.Database.Exec("SELECT * FROM users")
if err != nil {
log.Fatal(err) // --> pq: relation "users" does not exist
}
fmt.Printf("Tables: %v", r)
}
And then it fails on the c.Database.Exec("SELECT * FROM users") line which means that it's connected to the right database but it cannot find the table.
Out of ideas on this one - thoughts?
Edit
Feature request idea for postgresql folks: \connection_string -> returns the postgresql connection string given the current user inside of the database connected to.
Golang sql driver isn't clear about the order it expects. Ditch it. Save the whole connection string into a DATABASE URL variable and use that. Annoying but it seems to have solved the problem.
Pass this as a connection string: postgres://myname:password#localhost:5432/five_three_one_development?sslmode=disable and forget trying to build it up.
I have created an Api with golang and postgresql as database.
after several requests, the API crashes with an error 500 and a log that displays
pq : sorry , too many customers already
At first it was because I did not close rows when i select, so i have rows.close() all.
But it's not that because i have already this error.
Then saw the launch of the database takes only 3ms, I thought I should start and close the database on every request to reset all connections,
but thinking about it a little more, this is nonsense.
So I ask you, how this error works , is that the client connections are reset after a certain time or connection is cut off until a server reboot for client?
If it resets after a certain time , what are the disadvantages of increasing the maximum number of client connection?
My code:
I open my db like this at start of program :
var gest Gestion
type Gestion struct {
Db *sql.DB
DbLog *sql.DB
}
func InitDbUser() *sql.DB {
dbinfo := fmt.Sprintf("user=%s password=%s dbname=%s sslmode=disable", DB_USER, DB_PASSWORD, DB_NAME)
db, err := sql.Open("postgres", dbinfo)
LogFatalError(err)
err2 := db.Ping()
LogFatalError(err2)
return db
}
func main() {
gest.Db = InitDbUser()
defer gest.Db.Close()
//routing is here
}
And when i use this request in my psql :
select min_val,max_val from pg_settings where name='max_connections';
I get hat :
min_val | max_val
---------+---------
1 | 8388607
Sorry for my english, i hope you understand what I ask :)
You can check the max_connection setting of PG, that might be the problem here:
select min_val,max_val from pg_settings where name='max_connections'
I am having a small problem with datasnap in delphi Xe5.
I need to run dynamic queries on the server side. I am using an ADO connection on the server methods.
Server Procedure:
var
qryNew: TADOQuery;
dspNew: TDatasetProvider;
begin
qryNew := TADOQuery.Create(nil);
qryNew.Connection := Adoconnection1;
qryNew.SQL.Text := SQL;
qryNew.Name := 'qry'+IntToStr(1);
dspNew := TDatasetProvider.Create(nil);
dspNew.Name := 'dsp'+IntToStr(1);
dspNew.Dataset := qryNew;
qryNew.Open;
Result := dspNew.Name;
end;
Client side procedure:
ClientDataset1.ProviderName :=clientmodule3.ServerMethods1Client.GetDataForClient('Select top 10 * from ODBC.trans_day_2009_1111;');
On the main form i have a SQLconnection, DSProvider connection and a client dataset. When I try to set the provider name for the client with the above code, i get the error "Remote error: Provider not exported : DSP1"
Usually (not always), error messages are helpful if you spend the time to understand them. If it says the provider is not exported, you should have checked why it wasn't - i.e. the doc says:
"To enable the remote data module to pass calls to the provider, the provider's Exported property must be True, and its Owner property must specify the remote data module."
http://docwiki.embarcadero.com/Libraries/XE5/en/Datasnap.Provider.TDataSetProvider
Your provider has no owner.
The output of sql commands that is visible to users who interactively run SQL commands from SQL Server Management studio, is different than the output you get back from executing an ADO command or ADO query object.
USE [DBNAME]
BACKUP DATABASE [DBNAME] TO
DISK = 'C:\SqlBackup\Backup.mdf'
The successful completion output is like this:
Processed 465200 pages for database 'DBNAME', file 'filename' on file 2.
Processed 2 pages for database 'DBNAME', file 'filename_log' on file 2.
BACKUP DATABASE successfully processed 465202 pages in 90.595 seconds (40.116 MB/sec).
When I execute either a TADOCommand or TADOQuery with the CommandText or SQL set as above, I do not get any such output. How do I read this "secondary output" from the execution of an SQL command? I'm hoping that perhaps via some raw ADO operations I might be able to execute a command and get back the information above, for success, as well as any errors in performing an Sql backup.
Update: The answer below works better for me than my naive attempt, which did not work, using plain Delphi TADOCommand and TADOConnection classes:
create TADOCommand and TADOConnection.
execute command.
get info-messages back.
The problem I experienced in my own coding attempts, is that my first command is "use dbname" and the only recordset I traversed in my code, was the results of the "use dbname" command, not the second command I was executing. The accepted answer below traverses all recordsets that come back from executing the ADO command, and thus it works much better. Since I'm doing all this in a background thread, I actually think it's better to create the raw Com Objects anyways, and avoid any VCL entanglement in my thread. The code below could be a nice component if anybody is interested, let me know and I might make an open source "SQL Backup for Delphi" component.
Here is an example. I've tested it with D7 and MSSQL2000. And it adds to Memo1 all messages from server:
29 percent backed up.
58 percent backed up.
82 percent backed up.
98 percent backed up.
Processed 408 pages for database 'NorthWind', file 'Northwind' on file 1.
100 percent backed up.
Processed 1 pages for database 'NorthWind', file 'Northwind_log' on file 1.
BACKUP DATABASE successfully processed 409 pages in 0.124 seconds (26.962 MB/sec).
Also if it takes a long time consider to implement a WHILE loop not in the main thread.
uses AdoInt,ComObj;
.....
procedure TForm1.Button1Click(Sender: TObject);
var cmd : _Command;
Conn : _Connection;
RA : OleVariant;
rs :_RecordSet;
n : Integer;
begin
Memo1.Clear;
Conn := CreateComObject(CLASS_Connection) as _Connection;
Conn.ConnectionString := 'Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=NorthWind;Data Source=SQL_Server';
Conn.Open(Conn.ConnectionString,'','',Integer(adConnectUnspecified));
cmd := CreateComObject(CLASS_Command) as _Command;
cmd.CommandType := adCmdText;
cmd.Set_ActiveConnection(Conn);
cmd.CommandText := 'BACKUP DATABASE [NorthWind] TO DISK = N''c:\sql_backup\NorthWind'' WITH INIT , NOUNLOAD , NAME = N''NortWind backup'', NOSKIP , STATS = 10, NOFORMAT;';
rs:=cmd.Execute(RA,0,Integer(adCmdText));
while (rs<>nil) do
begin
for n:=0 to(Conn.Errors.Count-1)do begin
Memo1.Lines.Add(Conn.Errors.Item[n].Description);
end;
rs:=rs.NextRecordset(RA);
end;
cmd.Set_ActiveConnection(nil);
Conn.Close;
cmd := nil;
Conn := nil;
end;
I've found this thread (Russian) for stored procedure and correct it for BACKUP command.