Skip to content

Instantly share code, notes, and snippets.

@nyxz
Last active February 7, 2019 14:36
Show Gist options
  • Select an option

  • Save nyxz/2c57c558925c46ef063290b441c8f572 to your computer and use it in GitHub Desktop.

Select an option

Save nyxz/2c57c558925c46ef063290b441c8f572 to your computer and use it in GitHub Desktop.

Revisions

  1. nyxz revised this gist Feb 7, 2019. 1 changed file with 4 additions and 3 deletions.
    7 changes: 4 additions & 3 deletions xxd_and_postgresql_cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -8,9 +8,10 @@ Table

    ```sql
    CREATE TABLE system_properties (
    "name" varchar NOT NULL,
    value varchar NULL,
    data_value bytea NULL);
    "name" varchar NOT NULL,
    value varchar NULL,
    data_value bytea NULL
    );
    ```

    Copy file to DB as bytea:
  2. nyxz created this gist Feb 7, 2019.
    45 changes: 45 additions & 0 deletions xxd_and_postgresql_cheatsheet.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@

    Sometimes I need to copy some text file into the DB as `bytea` or get `bytea` from the DB as text file.

    For the examles I'll use the Firebase credentials file (in JSON format).

    Table
    ===

    ```sql
    CREATE TABLE system_properties (
    "name" varchar NOT NULL,
    value varchar NULL,
    data_value bytea NULL);
    ```

    Copy file to DB as bytea:
    ===
    Transform the file to hex using `xxd`:
    ```shell
    xxd -p /tmp/fcm_credentials.json | tr -d '\n' > /tmp/fcm_credentials.hex
    ```
    Then insert the file into the DB (using intermediate table):

    ```sql
    CREATE TABLE hexdump (hex text);

    \copy hexdump FROM '/tmp/fcm_credentials.hex';

    INSERT INTO system_properties ("name", value, data_value) VALUES ('FCM_CREDENTIALS', NULL, (SELECT decode(hex, 'hex') FROM hexdump));

    DROP TABLE hexdump;
    ```

    Read bytea from DB in original format:
    ===

    In `psql`:
    ```sql
    \copy (SELECT encode(data_value, 'hex') FROM system_properties WHERE name = 'FCM_CREDENTIALS') TO '/tmp/fcm_credentials.hex';
    ```

    Then in shell:
    ```shell
    ~> xxd -p -r /tmp/fcm_credentials.hex > /tmp/fcm_credentials.json
    ```