Вопрос

I created this SQL file and I want to upload this DDL (Data Definition Language) File to my PostgreSQL server. My server currently runs on Ubuntu 12.04.

CREATE DATABASE *;

--Create Tables
CREATE TABLE USER(
    user_id      varchar(36)    NOT NULL,
    username     varchar(36)    NOT NULL,
    user_type    varchar(36)    NOT NULL,
    name         varchar(36)    NOT NULL,
    email        varchar(36)    NOT NULL,
    picture      varchar(36)    NOT NULL
);

CREATE TABLE PRODUCT(
    product_id           varchar(36)    NOT NULL,
    product_name         varchar(36)    NOT NULL,
    product_type         varchar(36)    NOT NULL,
    product_price        varchar(36)    NOT NULL,
    product_available    varchar(36)    NOT NULL
);

CREATE TABLE TRANSACTION(
    transaction_id    varchar(36)    NOT NULL,
    user_id           varchar(36)    NOT NULL,
    product_id        varchar(36)    NOT NULL
);

CREATE TABLE INVENTORY(
    product_id           varchar(36)    NOT NULL,
    product_name         varchar(36)    NOT NULL,
    product_available    varchar(36)    NOT NULL
);
Это было полезно?

Решение

Running the script

To run DDL in the form of an SQL script, you should use psql, the same command you use to connect to the server interactively.

psql -h the.server.hostname -f my_script.sql the_database

I recommend using ON_ERROR_STOP=1 and -1, so it runs the DDL in a single transaction and aborts on any error.

psql -v ON_ERROR_STOP=1 -1 -h the.server.hostname -f my_script.sql the_database

Creating the DB

You can't create the database then immediately start creating tables. You must connect to some other DB to run create database and if you've connected to another DB, that's where the tables will get created.

You can put the psql command \c databasename in after the CREATE DATABASE, so it'll create the DB then switch to it. But it's generally a bad idea: if the create fails, the script will merrily keep on creating tables in the wrong DB unless you use ON_ERROR_STOP. You also can't use -1 (run in a single transaction) if you create and switch to a new DB.

Instead, manually CREATE DATABASE first, or do it with a separate script. That way you can run your DDL script sensibly.

The DDL

Your schema needs some work.

No primary keys.

No foreign keys.

Use of varchar(36) everywhere, even where it's wildly inappropriate like names and email addresses. Use the unbounded text type, or varchar with no length (they're the same thing in PostgreSQL anyway) if you don't have a need to constrain the length of a field for a specific reason.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top