linux – Connecting to db via SSH on docker fails

I’m trying to connect to a database via SSH from my docker container. I’m getting an error

could not connect to server: Connection refused
    Is the server running on host "0.0.0.0" and accepting
    TCP/IP connections on port 5433?

I have a script to open the port and it works fine on my development, OSX Catalina.

bin/tunnel.sh

#!/usr/bin/expect -f
spawn ssh -fNg -L 5432:0.0.0.0:5432 myserver
expect "connecting"
send "yes"
expect "assword:"
send "mypasswordr"
interact

ENTRYPOINT

set -e

if [ -f tmp/pids/server.pid ]; then
  rm tmp/pids/server.pid
fi

service cron restart
./bin/tunnel.sh
foreman start -f Procfile.production web

database.yml

production: &production
  <<: *default
  # sslmode: "require"
  host: 0.0.0.0
  # pool: 100

iis – CRL revocation check fails yet can retrieve file

I have an IIS server on a 2016 box (IIS v10 it says) which is being used to authenticate a unix server via a certificate. I have confirmed connectivity to the internal CRL server, I can telnet to it, I can download the file, and certutil comes with the below:

certutil -verify -urlfetch removed_for_privacy.cer
Issuer:
    CN=removed_for_privacy
    O=removed_for_privacy
    C=removed_for_privacy
  Name Hash(sha1): 35baf042268dc6dd33c1bcaf8656ab3339a2c06b
  Name Hash(md5): 0688a21d6c00b503fadf374e534604f1
Subject:
    CN=removed_for_privacy
    OU=removed_for_privacy
    O=removed_for_privacy
    L=removed_for_privacy
    S=removed_for_privacy
    C=removed_for_privacy
  Name Hash(sha1): 33db10b0a1303e8f58f12ea85a49e2d5c7956d28
  Name Hash(md5): d2162c234c3d235a530badf869764eeb
Cert Serial Number: 77001e3a38d80b8d528f0f4ed90000001e3a38

dwFlags = CA_VERIFY_FLAGS_CONSOLE_TRACE (0x20000000)
dwFlags = CA_VERIFY_FLAGS_DUMP_CHAIN (0x40000000)
ChainFlags = CERT_CHAIN_REVOCATION_CHECK_CHAIN_EXCLUDE_ROOT (0x40000000)
HCCE_LOCAL_MACHINE
CERT_CHAIN_POLICY_BASE
-------- CERT_CHAIN_CONTEXT --------
ChainContext.dwInfoStatus = CERT_TRUST_HAS_PREFERRED_ISSUER (0x100)
ChainContext.dwRevocationFreshnessTime: 216 Days, 6 Minutes, 47 Seconds

SimpleChain.dwInfoStatus = CERT_TRUST_HAS_PREFERRED_ISSUER (0x100)
SimpleChain.dwRevocationFreshnessTime: 216 Days, 6 Minutes, 47 Seconds

CertContext(0)(0): dwInfoStatus=102 dwErrorStatus=0
  Issuer: CN=removed_for_privacy
  NotBefore: 12/03/2021 05:48
  NotAfter: 12/03/2023 05:48
  Subject: CN=removed_for_privacy
  Serial: 77001e3a38d80b8d528f0f4ed90000001e3a38
  Template: 1.3.6.1.4.1.311.21.8.1475819.1923179.2641816.6959893.4978592.187.3822061.5349830
  Cert: c829af51c2f97f9336b150f348a5ed07cccc8326
  Element.dwInfoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER (0x2)
  Element.dwInfoStatus = CERT_TRUST_HAS_PREFERRED_ISSUER (0x100)
  ----------------  Certificate AIA  ----------------
  Verified "Certificate (0)" Time: 0
    (0.0) http://removed_for_privacy.crt

  ----------------  Certificate CDP  ----------------
  Verified "Base CRL (01fb)" Time: 0
    (0.0) http://removed_for_privacy.crl

  ----------------  Base CRL CDP  ----------------
  No URLs "None" Time: 0
  ----------------  Certificate OCSP  ----------------
  Verified "OCSP" Time: 0
    (0.0) http://removed_for_privacy/ocsp

  --------------------------------
    CRL (null):
    Issuer: CN=removed_for_privacy
    ThisUpdate: 04/05/2021 14:02
    NextUpdate: 06/05/2021 14:22
    CRL: fbd7722100ef6f4ab7d03c290aca62a85c9c6441
  Issuance(0) = 1.2.826.0.1.1833679.1.1.5.5.5
  Application(0) = 1.3.6.1.5.5.7.3.2 Client Authentication

CertContext(0)(1): dwInfoStatus=102 dwErrorStatus=0
  Issuer: CN=removed_for_privacy
  NotBefore: 07/09/2017 12:47
  NotAfter: 07/09/2025 12:57
  Subject: CN=removed_for_privacy
  Serial: 7700000002404ed3d5c1d87a1b000000000002
  Cert: b0e971dc53ea6a1e0b7d620704f7d16a6091a8d1
  Element.dwInfoStatus = CERT_TRUST_HAS_KEY_MATCH_ISSUER (0x2)
  Element.dwInfoStatus = CERT_TRUST_HAS_PREFERRED_ISSUER (0x100)
  ----------------  Certificate AIA  ----------------
  Verified "Certificate (0)" Time: 0
    (0.0) http://removed_for_privacy.crt

  ----------------  Certificate CDP  ----------------
  Verified "Base CRL (05)" Time: 0
    (0.0) http://removed_for_privacy.crl

  ----------------  Base CRL CDP  ----------------
  No URLs "None" Time: 0
  ----------------  Certificate OCSP  ----------------
  No URLs "None" Time: 0
  --------------------------------
    CRL 05:
    Issuer: CN=removed_for_privacy
    ThisUpdate: 30/09/2020 15:26
    NextUpdate: 30/10/2021 15:46
    CRL: 2e6fdb9adf169af6b8f029a2374a52099538abd3

CertContext(0)(2): dwInfoStatus=10c dwErrorStatus=0
  Issuer: CN=removed_for_privacy
  NotBefore: 31/08/2017 11:56
  NotAfter: 31/08/2037 11:56
  Subject: CN=removed_for_privacy
  Serial: 3bd2d21295368abd4a25a5dfb7c7921f
  Cert: bf8c3c705348b8d931d3853427f7f57bcf575d8d
  Element.dwInfoStatus = CERT_TRUST_HAS_NAME_MATCH_ISSUER (0x4)
  Element.dwInfoStatus = CERT_TRUST_IS_SELF_SIGNED (0x8)
  Element.dwInfoStatus = CERT_TRUST_HAS_PREFERRED_ISSUER (0x100)
  ----------------  Certificate AIA  ----------------
  No URLs "None" Time: 0
  ----------------  Certificate CDP  ----------------
  No URLs "None" Time: 0
  ----------------  Certificate OCSP  ----------------
  No URLs "None" Time: 0
  --------------------------------

Exclude leaf cert:
  Chain: da7d7a37bb99548aa5500003e5c9b83407fa115b
Full chain:
  Chain: 7ff925ccc3a676b7ad1b1e9ad8ae0c3fc86cd71e
------------------------------------
Verified Issuance Policies:
    1.2.826.0.1.1833679.1.1.5.5.5
Verified Application Policies:
    1.3.6.1.5.5.7.3.2 Client Authentication
Leaf certificate revocation check passed

IIS returns a solitary 403 13 error, more specifically:

2021-05-04 13:21:38 removed_for_privacy GET removed_for_privacy 443 - removed_for_privacy curl/7.29.0 - 403 13 2148081683 45020

SQL Server UPDATE Command Fails without error

Using SSMS running the below UPDATE command I get returned message says 1 row affected. but if I then follow it up with a Select and it shows that the row never updated.

This issue happens in SSMS and a custom application I built in C# using Entity Framework. I have since stopped using Entity Framework generated code and moved straight to a stored proc. All of 3 different ways of performing the same task I randomly get this issue. Sometimes it can be 100’s or 1000’s of updates before the issue happens again or it could be a few updates later it happens again.
I have run UPDATE STATISTICS, I have Rebuilt Indexes and Reorganized Indexes.

As a side note, I NEVER have an issue with INSERTs only UPDATEs we never DELETE any records. and total record count on the table is 201,741

UPDATE CreativeWorkFlowQueue
    SET CurrentIndicator = 'N'
WHERE CreativeWorkFlowQueueId = 198231

SELECT *
FROM CreativeWorkFlowQueue
WHERE CreativeWorkFlowQueueId = 198231

enter image description here

here is the table

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE (dbo).(CreativeWorkFlowQueue)(
    (CreativeWorkFlowQueueId) (int) IDENTITY(1,1) NOT NULL,
    (DigitalCampaignCreativeId) (int) NOT NULL,
    (WorkFlowQueueId) (int) NOT NULL,
    (CurrentIndicator) (char)(1) NOT NULL,
    (CreateDate) (datetime) NOT NULL,
    (LastUpdatedDate) (datetime) NOT NULL,
    (IsDeleted) (bit) NOT NULL,
PRIMARY KEY CLUSTERED 
(
    (CreativeWorkFlowQueueId) ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON (PRIMARY)
) ON (PRIMARY)
GO

ALTER TABLE (dbo).(CreativeWorkFlowQueue) ADD  CONSTRAINT (CreateDate defaults to utcDate on CreativeWorkFlowQueue)  DEFAULT (getutcdate()) FOR (CreateDate)
GO

ALTER TABLE (dbo).(CreativeWorkFlowQueue) ADD  CONSTRAINT (LastUpdatedDate defaults to utcDate on CreativeWorkFlowQueue)  DEFAULT (getutcdate()) FOR (LastUpdatedDate)
GO

ALTER TABLE (dbo).(CreativeWorkFlowQueue) ADD  CONSTRAINT (DF_CreativeWorkFlowQueue_IsDeleted)  DEFAULT ((0)) FOR (IsDeleted)
GO

ALTER TABLE (dbo).(CreativeWorkFlowQueue)  WITH CHECK ADD  CONSTRAINT (CreativeWorkFlowQueue DigitalCampaignCreativeId fk) FOREIGN KEY((DigitalCampaignCreativeId))
REFERENCES (dbo).(DigitalCampaignCreative) ((DigitalCampaignCreativeId))
GO

ALTER TABLE (dbo).(CreativeWorkFlowQueue) CHECK CONSTRAINT (CreativeWorkFlowQueue DigitalCampaignCreativeId fk)
GO

ALTER TABLE (dbo).(CreativeWorkFlowQueue)  WITH CHECK ADD  CONSTRAINT (CreativeWorkFlowQueue WorkFlowQueueId fk) FOREIGN KEY((WorkFlowQueueId))
REFERENCES (dbo).(WorkFlowQueue) ((WorkFlowQueueId))
GO

ALTER TABLE (dbo).(CreativeWorkFlowQueue) CHECK CONSTRAINT (CreativeWorkFlowQueue WorkFlowQueueId fk)
GO

EDIT Adding the Stored Proc that also has the same issue.

I did not include this stored proc simply due to the fact that it is complex and if a simple update doesn’t work I figured start there first.

CREATE PROCEDURE (dbo).(sp_WtvToRtl) 
    -- Add the parameters for the stored procedure here
    @tbl DCCIdList READONLY,    
    @WorkFlowQueueId int
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    
    DECLARE @dccList TABLE (
        CreativeWorkflowQueueId int null,
        DigitalCampaignCreativeId int null,
        WorkFlowQueueId int null,
        CurrentIndicator varchar(1) collate SQL_Latin1_General_CP1_CI_AS null,
        LastUpdatedDate datetime null
    )

    DECLARE @DCIDList TABLE(
        DigitalCampaignCreativeId int null
    )





        DECLARE @res TABLE (
        MergeAction VARCHAR(50) collate SQL_Latin1_General_CP1_CI_AS ,
        CreativeWorkFlowQueueId INT, 
        _Position INT
        )

    BEGIN TRANSACTION t1

    BEGIN TRY
        INSERT INTO @dccList (CreativeWorkflowQueueId, DigitalCampaignCreativeId,LastUpdatedDate,WorkFlowQueueId,CurrentIndicator)
        select CreativeWorkflowQueueId, DigitalCampaignCreativeId,LastUpdatedDate,WorkFlowQueueId, 'N' as CurrentIndicator from 
        dbo.CreativeWorkFlowQueue Where CurrentIndicator = 'Y' 
        and IsDeleted = 0
        and DigitalCampaignCreativeId In 
        (SELECT DigitalCampaignCreativeId FROM VRF.DigitalCampaignCreative 
        WHERE IsDeleted = 0 and SfClosed = 0 
        and DccId in (Select DccId COLLATE SQL_Latin1_General_CP1_CI_AS from @tbl)
        )
         
         INSERT INTO @DCIDList 
         SELECT DigitalCampaignCreativeId FROM @dccList
         GROUP BY DigitalCampaignCreativeId

        INSERT INTO @dccList (DigitalCampaignCreativeId,WorkFlowQueueId,CurrentIndicator)
        select DigitalCampaignCreativeId, @WorkFlowQueueId as WorkFlowQueueId, 'Y' as CurrentIndicator from 
        @DCIDList


        MERGE vrf.CreativeWorkFlowQueue a
        USING 
            (
            SELECT 
                x.CreativeWorkflowQueueId,
                x.DigitalCampaignCreativeId,
                x.LastUpdatedDate,
                x.WorkFlowQueueId,
                x.CurrentIndicator 
            FROM @dccList x
            ) stg  
    
        ON stg.CreativeWorkflowQueueId = a.CreativeWorkflowQueueId

        WHEN MATCHED THEN
            UPDATE SET 
                a.CurrentIndicator  = stg.CurrentIndicator,
                a.LastUpdatedDate = getutcdate()
        WHEN NOT MATCHED THEN
            INSERT 
                (
                    CurrentIndicator,
                    DigitalCampaignCreativeId,
                    WorkFlowQueueId
                )
            VALUES 
                (
                    stg.CurrentIndicator, 
                    stg.DigitalCampaignCreativeId, 
                    stg.WorkFlowQueueId
                )  
            -- ********************************************************************
            -- Remove this if you don't need to return the results below.
            OUTPUT 
                INSERTED.CreativeWorkFlowQueueId,
                $action 
            INTO @res (CreativeWorkFlowQueueId, MergeAction);
            -- ********************************************************************


        COMMIT TRANSACTION t1

    END TRY
    BEGIN CATCH

        DECLARE @ErrorMessage NVARCHAR(MAX), @ErrorSeverity INT, @ErrorState INT;
        SELECT @ErrorMessage = ERROR_MESSAGE() + ' Line ' + CAST(ERROR_LINE() AS NVARCHAR(5)), @ErrorSeverity = ERROR_SEVERITY(), @ErrorState = ERROR_STATE();
        ROLLBACK TRANSACTION t1
        --RAISERROR(@ErrorMessage, @ErrorSeverity, @ErrorState);
        SELECT 'FAILED' MergeAction,
                s.CreativeWorkflowQueueId,
                s.DigitalCampaignCreativeId,
                '' DccId,
                s.WorkFlowQueueId,
                s.CurrentIndicator,
                null CreateDate,
                null LastUpdatedDate,
                null IsDeleted,
                @ErrorMessage ErrorMessage
        FROM @dccList s
    END CATCH


    -- Normally, I would not have this.  But this will simulate
    -- what EF does if you need it.
    SELECT 
        r.MergeAction,
        a.CreativeWorkFlowQueueId,
        a.DigitalCampaignCreativeId,
        d.DccId,
        a.WorkFlowQueueId,
        a.CurrentIndicator,
        a.CreateDate, 
        a.LastUpdatedDate,
        a.IsDeleted,
        '' ErrorMessage
    FROM vrf.CreativeWorkFlowQueue a 
    JOIN @res r ON a.CreativeWorkFlowQueueId = r.CreativeWorkFlowQueueId
    JOIN vrf.DigitalCampaignCreative d ON a.DigitalCampaignCreativeId = d.DigitalCampaignCreativeId
    ORDER BY 
        r.MergeAction,
        r._Position


END

The User-Defined Table Type is this.

CREATE TYPE (dbo).(DCCIdList) AS TABLE(
    (DccId) (nvarchar)(18) NULL
)

Ping fails locally but online tools work

Recently changed the server and now when I am connect to WHM or Cpanel or working with FTP..after few mins…the connection times out and pi… | Read the rest of https://www.webhostingtalk.com/showthread.php?t=1844989&goto=newpost

PostgreSQL connection URI fails, but parameters work

Running postgreSQL 13.2 with ssl on.

I need to connect to a database from a third party application that requires a connection URI, but it is not working. So I tested connecting with psql using two different formats with the same credentials. One worked and one didn’t.

The following command logs me into mydb as user myuser:

# psql -U myuser -d mydb -h 127.0.0.1 -p 5432 -W
Password:
psql (13.2 (Debian 13.2-1.pgdg100+1))
SSL connection (protocol: TLSv1.3, cipher: TLS_AES_256_GCM_SHA384, bits: 256, compression: off)
Type "help" for help.

mydb=>

However this command fails:

# psql postgresql://myuser:MYPASSWORD@127.0.0.1:5432/mydb?sslmode=require
psql: error: FATAL: password authentication failed for user "myuser"

I am using exactly the same credentials. I’ve verified it more than 10 times. Removing “sslmode=require” does not fix the problem.

My pg_hba.conf file contains:

host   mydb   myuser   127.0.0.1/32   password

I made it the first line in my pg_hba.conf file, so it can’t be getting hung up on any other line.

What am I doing wrong?

ubuntu – add-apt-repository fails due to gpg key timeout

I am running a Mail-in-a-Box server on Ubuntu 18.04. As part of the setup/update script, it attempts to execute the command add-apt-repository -y ppa:certbot/certbot. This fails with the following error message:

FAILED: add-apt-repository -y ppa:certbot/certbot
-----------------------------------------
Error: retrieving gpg key timed out.
-----------------------------------------

When I try to run the command manually, I get the following error:

Error: retrieving gpg key timed out.

Things I have already tried

I have tried all of the following and none of them resolved my issue. If there
was an obvious way to undo what I tried, I undid it before trying the next
thing.

Reboot

I rebooted the server with sudo reboot.

apt-get –allow-releaseinfo-change

This person
had a similar problem and solved it with
sudo apt-get --allow-releaseinfo-change update.

Let’s Encrypt down

It has been suggested
(twice)
that Let’s Encrypt may be
down. However, I have tried running the command at various times, their
status dashboard doesn’t indicate any major
issues and it runs fine on a different Ubuntu 18.04 machine I set up for
testing.

Wrong nameserver

This user had a similar issue, which he solved by editing his /etc/resolv.conf file.
My file had the contents nameserver 127.0.0.1. I know that Mail-in-a-Box can
also function as a nameserver, so I assume it is fine. For thoroughness’ sake
I changed it to nameserver 8.8.8.8, but this didn’t fix the problem.

apt autoclean & autoremove

A commenter suggested
running sudo apt autoclean && sudo apt autoremove.

Switch keyserver

This user suggests editing the
~/.gnupg/gpg.conf file to use a different keyserver:
keyserver keys.openpgp.org

This other user
does what appears to be the same thing but inline. I tried
sudo add-apt-repository -k hkp://keyserver.ubuntu.com:80 -y ppa:certbot/certbot
and
sudo add-apt-repository -k hkp://pool.sks-keyservers.net:80 -y ppa:certbot/certbot.

This third user apparently tries to
change the keyserver and port in a different way. I tried his command
gpg --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 94558F59.

A fourth person suggested the
following two commands:
gpg --keyserver hkp://keys.gnupg.net --recv-keys 94558F59 and
gpg --keyserver hkp://pgp.mit.edu --recv-keys 94558F59.

Disable firewall

This person tried disabling
their firewall before running the command. So did I with sudo ufw disable.

Someone else
thought unblocking port 11371 might work. I tried sudo ufw allow 11371.

I also don’t believe that an ISP-firewall is causing issues. I am running a VPS
from Vultr and my testing-machine (on which it works) is also hosted by them.


Miscellaneous

I believe a fresh install of the operating system would alleviate this issue.
However, I would prefer not to do this if at all possible.

I was unsure, whether this question would better fit the ask ubuntu or the server fault Stackexchange so I took the liberty of posting it on both sites.

error – Time Machine fails shortly after starting to prepare backup

I have a problem with the Time Machine backup: 1-2 mins after starting the process (Backup is being prepared), it stops.

Console logs:

Backup failed (304: BACKUP_FAILED_PREFLIGHT_STAGE_SNAPSHOT_DIFFING)

Failed to collect events for “Macintosh SSD – Daten” (device:
/dev/disk1s1 mount: ‘/System/Volumes/Data’ fsUUID:
37BA4BE5-ACF2-37EE-81E7-41B277B3CACE eventDBUUID:
E0435E75-595E-4699-A798-47ADB7F3E85A), error Error
Domain=com.apple.backupd.ErrorDomain Code=304 “(null)”

Failed to enumerate snapshot diffs, error: Error
Domain=NSPOSIXErrorDomain Code=83 “Device error”

I switched already the HDD, it runs for 2-3 weeks and then I get the same error.

Anybody can help?

Migration Plus entity_lookup fails – Drupal Answers

I’m trying to generate a taxonomy term if this does not already exist.
the migration file:

The taxonomy bundle name is function and the column in the spreadsheet
containing the values is ‘Functie’. However, I’m getting the following error:

(error) Error: Call to a member function getConfig() on null
in
Drupalmigrate_plusPluginmigrateprocessEntityLookup->determineLookupProperties() (line 217 of
/var/www/html/web/modules/contrib/migrate_plus/src/Plugin/migrate/process/EntityLookup.php)

/var/www/html/web/modules/contrib/migrate_plus/src/Plugin/migrate/process/EntityLookup.php(182):
Drupalmigrate_plusPluginmigrateprocessEntityLookup->determineLookupProperties(‘field_function’)

/var/www/html/web/modules/contrib/migrate_plus/src/Plugin/migrate/process/EntityGenerate.php(116):
Drupalmigrate_plusPluginmigrateprocessEntityLookup->transform(‘Medewerker’,
Object(Drupalmigrate_toolsMigrateExecutable),
Object(DrupalmigrateRow), ‘field_function’)

/var/www/html/web/core/modules/migrate/src/MigrateExecutable.php(394):
Drupalmigrate_plusPluginmigrateprocessEntityGenerate->transform(‘Medewerker’,
Object(Drupalmigrate_toolsMigrateExecutable),
Object(DrupalmigrateRow), ‘field_function’)

/var/www/html/web/core/modules/migrate/src/MigrateExecutable.php(203):
DrupalmigrateMigrateExecutable->processRow(Object(DrupalmigrateRow))

/var/www/html/vendor/drush/drush/includes/drush.inc(223): DrupalmigrateMigrateExecutable->import()

/var/www/html/vendor/drush/drush/includes/drush.inc(214): drush_call_user_func_array(Array, Array)

/var/www/html/web/modules/contrib/migrate_tools/src/Commands/MigrateToolsCommands.php(766):
drush_op(Array)

(internal function): Drupalmigrate_toolsCommandsMigrateToolsCommands->executeMigration(Object(DrupalmigratePluginMigration),
‘profiles’, Array)

/var/www/html/web/modules/contrib/migrate_tools/src/Commands/MigrateToolsCommands.php(321):
array_walk(Array, Array, Array)

(internal function): Drupalmigrate_toolsCommandsMigrateToolsCommands->import(‘profiles’,
Array)

/var/www/html/vendor/consolidation/annotated-command/src/CommandProcessor.php(257):
call_user_func_array(Array, Array)

/var/www/html/vendor/consolidation/annotated-command/src/CommandProcessor.php(212):
ConsolidationAnnotatedCommandCommandProcessor->runCommandCallback(Array,
Object(ConsolidationAnnotatedCommandCommandData))

/var/www/html/vendor/consolidation/annotated-command/src/CommandProcessor.php(178):
ConsolidationAnnotatedCommandCommandProcessor->validateRunAndAlter(Array,
Array, Object(ConsolidationAnnotatedCommandCommandData))

/var/www/html/vendor/consolidation/annotated-command/src/AnnotatedCommand.php(302):
ConsolidationAnnotatedCommandCommandProcessor->process(Object(SymfonyComponentConsoleOutputConsoleOutput),
Array, Array, Object(ConsolidationAnnotatedCommandCommandData))

/var/www/html/vendor/symfony/console/Command/Command.php(255):
ConsolidationAnnotatedCommandAnnotatedCommand->execute(Object(DrushSymfonyDrushArgvInput),
Object(SymfonyComponentConsoleOutputConsoleOutput))

/var/www/html/vendor/symfony/console/Application.php(978): SymfonyComponentConsoleCommandCommand->run(Object(DrushSymfonyDrushArgvInput),
Object(SymfonyComponentConsoleOutputConsoleOutput))

/var/www/html/vendor/symfony/console/Application.php(255): SymfonyComponentConsoleApplication->doRunCommand(Object(ConsolidationAnnotatedCommandAnnotatedCommand), Object(DrushSymfonyDrushArgvInput),
Object(SymfonyComponentConsoleOutputConsoleOutput))

/var/www/html/vendor/symfony/console/Application.php(148): SymfonyComponentConsoleApplication->doRun(Object(DrushSymfonyDrushArgvInput),
Object(SymfonyComponentConsoleOutputConsoleOutput))

/var/www/html/vendor/drush/drush/src/Runtime/Runtime.php(118):
SymfonyComponentConsoleApplication->run(Object(DrushSymfonyDrushArgvInput),
Object(SymfonyComponentConsoleOutputConsoleOutput))

/var/www/html/vendor/drush/drush/src/Runtime/Runtime.php(49): DrushRuntimeRuntime->doRun(Array,
Object(SymfonyComponentConsoleOutputConsoleOutput))

/var/www/html/vendor/drush/drush/drush.php(72): DrushRuntimeRuntime->run(Array)

/var/www/html/vendor/drush/drush/includes/preflight.inc(18): require(‘/var/www/html/v…’)

phar:///usr/local/bin/drush/bin/drush.php(141): drush_main()
/usr/local/bin/drush(10): require(‘phar:///usr/loc…’)

If anyone could point out what’s going wrong, by all means, enlighten me because I have no clue what’s going on, the configuration seems right to me.

php – Avoid database insertion when another query fails

Before starting, I’d like to say I’m not an advanced user on PHP, I’m still learning.

I’m working on an application where I have a class to handle all database operations and I’m trying to simplify this process and catch errors in a better way. For example, when I want to insert a new user I need to execute a couplo of queries to different tables in my database.

First of all, let me show the class that handles the database connection.

# database.class.php
namespace Playground;

use PDO;

class Dbh {
  private static $instance;
  private $conn = null;
  private $database = 'playground';
  private $host = 'localhost';
  private $user = 'root';
  private $pass = 'root';
  private $option = array(
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::MYSQL_ATTR_INIT_COMMAND => "SET time_zone = '-3:00', lc_time_names='pt_BR'"
  );

  /**
   * Construct
   */
  private function __construct() {
    $this->conn = new PDO(
      'mysql:charset=utf8mb4;host='.$this->host.';dbname='.$this->database,
      $this->user,
      $this->pass,
      $this->option
    );
  }

  /**
   * Prevent class cloning
   */
  private function __clone() {}

  /**
   * Initialize an instance of this class
   */
  public static function init() {
    if (!self::$instance) {
      self::$instance = new Dbh();
    }
    
    return self::$instance;
  }

  /**
   * Close database connection
   */
  public function close() {
    $this->conn = null;
  }

  /**
   * Load all data from a table and return as an array.
   * 
   * @param String  $sql Query to be executed
   * @param Array   $param Parameters to be binded
   * 
   * @return Array
   */
  public function load(String $sql, Array $param = null) {
    $q = $this->conn->prepare($sql);
    $q->execute($param);

    return  $q->fetchAll();
  }

  /**
   * Insert new record to the database and return the ID.
   * 
   * @param String  $sql Query to be executed
   * @param Array   $param Parameters to be binded
   * 
   * @return Number
   */
  public function insert(String $sql, Array $param = null) {
    $q = $this->conn->prepare($sql);
    $q->execute($param);

    return $this->conn->lastInsertId();
  }
}
# user.class.php

/**
 * Register a new user
 *
 * @param Object $jwt JWT Token
 * @param Object $post Data via $_POST
 *
 * @return Response<Null|Object>
 */
public function addUser(object $jwt, object $post) {
  // Init Dbh
  $dbh = Dbh::init();

  // Check for required fields
  if (!Utils::checkParams($post, $this->userAddRequiredParams)) {
    return $this->response->error('validation');
  }

  // Add new user
  $params = (
    ':id_group' => $post->id_group,
    ':master' => $post->master,
    ':email' => $post->email,
    ':pass' => Auth::generatePassword(), // Random for new users
  );
  $id_user = $dbh->insert("INSERT INTO tb_user
    (id_group, master, email, pass) VALUES
    (:id_group, :master, :email, :pass)
  ", $params);
  if (!$id_user) {
    Log::error($jwt->uid, 'post', 'user', 'Fail to add new user. tb_user', $params);
    return $this->response->error();
  }

  // Add user detail
  $params = (
    ':id_user' => $id_user,
    ':first_name' => ucfirst($post->first_name),
    ':last_name' => $post->last_name,
    ':birthdate' => Utils::converterData($post->birthdate),
    // (...) There are many other fields here
  );
  $id_user_info = $dbh->insert("INSERT INTO tb_user_info
    (id_user, first_name, last_name, birthdate, ...) VALUES
    (:id_user, :first_name, :last_name, :birthdate, ...)
  ", $params);
  if (!$id_user_info) {
    Log::error($jwt->uid, 'post', 'user', 'Fail to add new user. tb_user_info', $params);
    return $this->response->error();
  }

  // Add user address
  $params = (
    ':id_user' => $id_user,
    ':street' => $post->street,
    ':zipcode' => $post->zipcode,
    // (...) There are many other fields here
  );
  $id_address = $dbh->insert("INSERT INTO tb_user_address
    (id_user, street, zipcode, ...) VALUES
    (:id_user, :street, :zipcode, ...)
  ", $params);
  if (!$id_address) {
    Log::error($jwt->uid, 'post', 'user', 'Fail to add new user. tb_user_address', $params);
    return $this->response->error();
  }

  // Create record to sync user and group
  $params = (
    ':id_author' => $jwt->uid,
    ':id_group' => $post->id_group,
    ':id_user' => $id_user,
  );
  $insert = $dbh->insert("INSERT INTO tb_user_group
    (id_author, id_group, id_user) VALUES
    (:id_author, :id_group, :id_user)
  ", $params);
  if (!$insert) {
    Log::error($jwt->uid, 'post', 'user', 'Fail to add new user. tb_user_group', $params);
    return $this->response->error();
  }

  // Send an welcome e-mail to the new user
  // (...)
  // Some other irrelevant stuff

  // Return success
  $user = $this->loadUser($id_user);
  return $this->response->success('User added successfully', $user);
}

This code is working as expected. But let’s say that, for some reason, we were unable to properly insert the user address. Then the function will break at the address and will generate an invalid user registration, since it won’t have the address.

I know that there is an option to do a rollback, but I don’t know how it works, since I never did it before. By looking at some other materials I found something based on a Try/Catch method for all the database queries, but when I tried, I couldn’t make the error happen, I mean, I made an invalid query myself to test it but the catch method never gets executed. This is what I did.

/**
 * Register a new 
 *
 * @param Object $jwt JWT Token
 * @param Object $post Data via $_POST
 *
 * @return Response<Null|Object>
 */
public function addUser(object $jwt, object $post) {
  // Init Dbh
  $dbh = Dbh::init();

  // Check for required fields
  if (!Utils::checkParams($post, $this->userAddRequiredParams)) {
    return $this->response->error('validation');
  }

  try {
    // Note: This is the same query as before, I'm justi simplifying

    // Add new user
    $params = (':id_group' => $post->id_group, (...));
    $id_user = $dbh->insert("INSERT INTO tb_user ...", $params);

    // Add user detail
    $params = (':id_user' => $id_user, (...));
    $id_user_info = $dbh->insert("INSERT INTO tb_user_info ...", $params);

    // Add user address
    $params = (':id_user' => $id_user, ...);
    $id_address = $dbh->insert("INSERT INTO tb_user_address ...", $params);

    // Create record to sync user and group
    $params = (':id_author' => $jwt->uid, (...));
    $insert = $dbh->insert("INSERT INTO tb_user_group ...", $params);
  } catch (Throwable $th) {
    $dbh->rollback();
    Log::error($jwt->uid, 'post', 'user', 'Fail to add new user. tb_user', $params);
    return $this->response->error();
  }

  // Send an welcome e-mail to the new user
  // (...)
  // Some other irrelevant stuff

  // Return success
  $user = $this->loadUser($id_user);
  return $this->response->success('User added successfully', $user);
}

What should I do in this case? Or what can be done to improve this process and ensure that all steps are inserted properly on the database? This is a common flow I have in other areas on the same application as well.

Magento V1.9* What happens when an Order Status has no order state – Paypal fails to cancel order after disputed transaction

Magento V1.9.4.5

Interesting edge case came to my desk

Problem paypal IPN fails to create credit memo and cancel order after paypal has dispute and reversed the transacti

Date/Time week later after shipped !! PM|PayPal Canceled Reversal
Customer Not Notified
IPN “Canceled_Reversal”. A reversal has occurred on this transaction due to a complaint about the transaction from your customer. Transaction amount $. Transaction ID: “”

Date/Time PM|PayPal Reversed
Customer Not Notified
IPN “Dispute”. Case type “Dispute”. Case ID “” Buyer claims that he did not receive goods or service.

Date/Time PM|PayPal Reversed
Customer Not Notified
IPN “Reversed”. A reversal has occurred on this transaction due to a complaint about the transaction from your customer. Transaction amount -$ Transaction ID: “”

Date/Time PM|Complete
Customer Not Notified
Riskified Status: fulfilled

Date/Time PM|Complete
Customer Notified

Date/Time PM|Processing
Customer Not Notified
Riskified Status: fulfilled

Question: What happens when an Order Status has no order state as none of these order status had a assigned state
referring to magentodomain.com/index.php/admin/sales_order_status/

Question:
Is a blank state assigned “processing” by default ?

  • Our ERP picked this up as “processing” after disputed
    -whereas should be canceled
Status status code default status state code
PayPal Canceled Reversal paypal_canceled_reversal
PayPal Reversed paypal_reversed
Pending PayPal pending_paypal

Changed it to

Status status code default status state code
PayPal Canceled Reversal paypal_canceled_reversal No canceled [Canceled]
PayPal Reversed paypal_reversed No holded [On Hold]
Pending PayPal pending_paypal
  • Pending Paypal left blank because this never appears in 7yrs of orders

Question 2 explain default please

  1. what happens if default is blank
  2. what happens when default is yes
  3. what happens when default is no