Vapor PostgreSQL Error: invalidSQL("ERROR: relation \"pages\" already exists\n") - swift

I am trying to revert a PostgreSQL database with with the Vapor command:
vapor run prepare --revert -y
I get this out put:
Running mist...
Are you sure you want to revert the database?
y/n>yes
Reverting Post
Reverted Post
Removing metadata
Reversion complete
In case you are wondering, I have tried doing this multiple times, so the Post class gets prepared, but the others don't.
This command reverts that tables for all the models, except one (There are four total).
For some reason the 'pages' table will not revert.
And when I try running the app after reverting the database, I get this error:
invalidSQL("ERROR: relation \"pages\" already exists\n")
Here is the database preparation code for the model:
extension Page: Preparation {
static func prepare(_ database: Database) throws {
try database.create("pages", closure: { post in
post.id()
post.string("content", length: 10000)
post.string("name")
post.string("link")
})
}
static func revert(_ database: Database) throws {
try database.delete("pages")
}
}

I managed to fix this by deleting the old DB:
dropdb `whoami`
Then creating a new one:
createdb `whoami`
Problem solved!

Related

Debugging connection PostgreSQL Loopback 4

Im on a mac(OS 10.14) using nodejs 14 and PostgresSQL 12.
I just installed Loopback4 and after following this tutorial Im not able to use any of the enpoints that use Models, ie that connect to Postgres, I constantly get a timeout.
It seems like its not even reaching the Postgres Server, but the error gives no information, just that the request times out.
There are no issues with the Postgres server since I can connect and request information with other nodejs applications to the same database.
I also tried to set this as the host host: '/var/run/postgresql/', same result.
I now tried the approach with a Docker container, setting the datasource files as follows:
import {inject, lifeCycleObserver, LifeCycleObserver} from '#loopback/core';
import {juggler} from '#loopback/repository';
const config = {
name: 'mydb',
connector: 'postgresql',
url: 'postgres://postgres:mysecretpassword#localhost:5434/test',
ssl: false,
};
// Observe application's life cycle to disconnect the datasource when
// application is stopped. This allows the application to be shut down
// gracefully. The `stop()` method is inherited from `juggler.DataSource`.
// Learn more at https://loopback.io/doc/en/lb4/Life-cycle.html
#lifeCycleObserver('datasource')
export class PostgresSqlDataSource extends juggler.DataSource
implements LifeCycleObserver {
static dataSourceName = 'PostgresSQL';
static readonly defaultConfig = config;
constructor(
#inject('datasources.config.PostgresSQL', {optional: true})
dsConfig: object = config,
) {
super(dsConfig);
}
}
With that same url I can log on my command line from my mac.
Is there a way to add logging and print any connection error? Other ways to debug it?
[UPDATE]
As of today Loopback4 Postgres connector does not work properly with Nodejs 14.
When starting the application, instead of running
npm start, you can set the debug string by running:
DEBUG=loopback:connector:postgresql npm start
If you want it to be more generic, you can use:
DEBUG=loopback:* npm start

Strange error when initializing Postgres database in FeathersJS

I am converting a FeathersJS system from MySQL to Postgres and facing some problems.
After changing the connection string
"mysql": "mysql://user:password#server:port/database"
to
"postgres": "postgres://user:password#server:port/database"
at config/default.json, I changed the dialect from mysql to pg at feathers/sequelize.js.
But when I started with npm run dev I got the following JSON error message, never seen before.
{
"_bitField":18087936,
"_fulfillmentHandler0":{
"name":"SequelizeConnectionError",
"parent":{
"name":"error",
"length":93,
"severity":"FATAL",
"code":"3D000",
"file":"postinit.c",
"line":"855",
"routine":"InitPostgres"
},
"original":{
"name":"error",
"length":93,
"severity":"FATAL",
"code":"3D000",
"file":"postinit.c",
"line":"855",
"routine":"InitPostgres"
}
},
"name":"SequelizeConnectionError",
"parent":{
"name":"error",
"length":93,
"severity":"FATAL",
"code":"3D000",
"file":"postinit.c",
"line":"855",
"routine":"InitPostgres"
},
"original":{
"name":"error",
"length":93,
"severity":"FATAL",
"code":"3D000",
"file":"postinit.c",
"line":"855",
"routine":"InitPostgres"
}
}
After researching a bit with no success, here I am to ask if someone has ever seen this message.
I already tried the dialect as pg and postgres at feathers/sequelize.js, just to check if it would make any difference, but it didn't.
A true beginner error! My fault!
When I created the Postgres (Docker) container, I forgot to create the database itself!
I created the role and gave it the needed permissions, but forgot to create the database corresponding to my connection string.
The Postgres error code mentioned in my question (3D000) corresponds to invalid_catalog_name, i.e., no database corresponding to the connection string.
One may easily check this at Postgres documentation, but I was mistakenly looking for this error code at FeathersJS documentation.

database does not exist - PostgreSQL in Server Side Swift using Vapor 3 and Fluent

I'm writing a web service in Swift using Vapor 3. I'm using FluentPostgreSQL for data persistence. I have a user model which conforms to both PostgreSQLModel, PostgreSQLMigration. The app builds correctly. However, when I run the app, I am getting the following error.
Fatal error: Error raised at top level: ⚠️ PostgreSQL Error: database "trialService" does not exist
- id: PostgreSQLError.server.fatal.InitPostgres
This is how my configure.swift looks like.
try services.register(FluentPostgreSQLProvider())
let configPSQL = PostgreSQLDatabaseConfig(hostname: "localhost", username: "imthath", database: "trialService")
let psql = PostgreSQLDatabase(config: configPSQL)
var databases = DatabasesConfig()
databases.add(database: sqlite, as: .sqlite)
databases.add(database: psql, as: .psql)
services.register(databases)
As you can see I was earlier using SQLite and now I am trying to use PostgreSQL for some models including User. I did not get any error when I was only SQLite.
You need to create the database from the terminal before your Vapor app can connect to it:
createdb trialService

Flyway - Flyway Schema migration failed

I have successfully configured spring boot with a new project to work
with flyway
Migrated with the Postgres database from the version 0001.0 to 0008.0
I have made manually alter the script in local but
flyway migration getting failed.
Sample Error message:
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'flywayInitializer' defined in class path
resource
[org/springframework/boot/autoconfigure/flyway/FlywayAutoConfiguration$FlywayConfiguration.class]:
Invocation of init method failed; nested exception is
org.flywaydb.core.api.FlywayException: Validate failed: Migration
checksum mismatch for migration version 0006.0
How to alter the database tables without affecting flyway script from the flyway_schema_history?
For example, I need to change the table name using alter command but executing the flyway migration script without failed.
Any suggestions, Kindly appreciated.
Note:- I don't want to remove the script entries from the table flyway_schema_history.
There are a few ways to do this:-
1) Create a new script file with incremented version. Put your DDL commands to alter the table in this file. Then run migration.
2) If you don't want to delete the entry from the schema_version table, you can change the checksum value in that table. To calculate checksum, use the following method copied from org.flywaydb.core.internal.resolver.sql.SqlMigrationResolver. You can pass null for resource parameter:-
/**
* Calculates the checksum of this string.
*
* #param str The string to calculate the checksum for.
* #return The crc-32 checksum of the bytes.
*/
/* private -> for testing */
static int calculateChecksum(Resource resource, String str) {
final CRC32 crc32 = new CRC32();
BufferedReader bufferedReader = new BufferedReader(new StringReader(str));
try {
String line;
while ((line = bufferedReader.readLine()) != null) {
crc32.update(line.getBytes("UTF-8"));
}
} catch (IOException e) {
String message = "Unable to calculate checksum";
if (resource != null) {
message += " for " + resource.getLocation() + " (" + resource.getLocationOnDisk() + ")";
}
throw new FlywayException(message, e);
}
return (int) crc32.getValue();
}
3) If you are using Flyway Pro version 5+, you can rollback the migration https://flywaydb.org/getstarted/undo.
The answers here are outdated but can still help you.
It sounds like you might be in one of two situations:
You want to re-run a versioned migration. This isn't really how flyway works, as Kartik has suggested, create a new versioned migration to alter the table.
A migration file has been modified and you want to leave it that way and run new ones (eg 0009.0). In this situation you can try:
Run repair. Which will recalculate the checksums (among other things).
Turn off the validateOnMigrate option which will not fail a migration if there are modified migration files.
To solve this error locally without dropping your whole db:
Fix the migration error which caused the root problem
Disconnect your db server
Open the table "flyway_schema_history" which would be created automatically
Delete the rows with the versions that are causing the mismatch problem
Open the tables that have columns depending on the conflict migrations and drop those columns (if needed)
Run again your db server with the new migrations

FluentMigrator rollback not working

I see the related question already there. FluentMigrator Failed Migrations Don't Rollback? and Rollback to a specfic Migration in FluentMigrator. But unfortunately i can't solve my rollback issue with this solution. I am using FluentMigrator to versioning database.
My migration code :
using FluentMigrator;
namespace WebCruiter.Candidate.DBMigration.Migrations.R2016_6
{
[Migration(20160908000908, "USERSTORY")]
public class Migration20160908000908 : AutoReversingMigration
{
public override void Up()
{
Create.Column("TestUrl").OnTable("JobApplication").AsString(500).Nullable();
}
}
}
And my attempt to rollback this version(20160908000908) from command line:
migrate.exe -c "server=(LocalDB)\MSSQLLocalDB;Initial Catalog=Candidate;Integrated Security=True" -db sqlserver2014 -a ".\..\..\..\WebCruiter.Candidate.DBMigration\bin\Debug\FluentMigrator.dll" -t rollback:20160908000908
Without rollback column TestUrl from JobApplication it shows :
Can anybody help me out where i made a mistake ?
Because you need to give the runner the number of the migration before the one you want to rollback to. So say you have migrations 1, 2, and 3. And you want to rollback 3, you would give the runner 2
What you are giving the runner at the moment is not that, give it the migration before '20160908000908'.
This is basically what was written in Rollback to a specfic Migration in FluentMigrator, You write the number of the migration you want as your last one, not the number of migration you want to rollback to.