sql-server 迁移数据库到postresql 方案Babelfish for PostgreSQL14.2 Ubuntu 20.4

sql-server 迁移数据库到postresql 方案 数据库 Postgresql 14.2

参考:
https://github.com/babelfish-for-postgresql/babelfish_extensions/blob/BABEL_1_X_DEV/contrib/README.md

https://mp.weixin.qq.com/s/-Rwf9R5utg_wYi91ZcUsFA
https://www.modb.pro/db/181528

https://www.modb.pro/db/237005
https://www.modb.pro/db/402380

This package includes 4 extensions:
    babelfishpg_tsql
        Supports the tsql language.
    babelfishpg_tds
        Supports the tds connection.
    babelfishpg_common
        Supports the various datatypes in MSSQL.
    babelfishpg_money
        supports the money type in MSSQL. This is a variation of the opensource fixeddecimal extension.
before setup config env

postgres@iZbp179u0bgzhoi4l5mu3lZ:~$ more /etc/issue
Ubuntu 20.04.4 LTS

postgres@iZbp179u0bgzhoi4l5mu3lZ:~$ cmake -version
cmake version 3.20.6

CMake suite maintained and supported by Kitware (kitware.com/cmake).

vi  .bashrc
export PATH="$PATH:/opt/mssql-tools/bin"

export EXTENSIONS_SOURCE_CODE_PATH="/opt/babelfish_extensions"

export INSTALLATION_PATH=/opt/postgres

export PG_CONFIG=$INSTALLATION_PATH/bin/pg_config
export PG_SRC=/opt/postgresql_modified_for_babelfish
export cmake=/usr/local/bin/cmake
~                                     

How do I build the extensions?

The following build instructions comply with Ubuntu 20.04 and Amazon Linux 2 environment.
Build the Postgres engine

1 First install dependent tools and libraries
Install postgresql-devel, libicu, libxml2, openssl and uuid-devel packages in order to build Babelfish.

You'll also need to install gcc, gcc-c++, java and bison.
    sudo apt-get install uuid-dev openjdk-8-jre \
                        libicu-dev libxml2-dev openssl libssl-dev python-dev \
                        libossp-uuid-dev libpq-dev pkg-config g++ build-essential bison 
For RHEL-flavoured distributions, this is the command for dealing with the required dependencies:
    sudo yum install libicu-devel libxml2-devel \
                     openssl-devel uuid-devel postgresql-devel gcc gcc-c++ java
2 Now it’s time to build the Postgres engine.
 In the Postgres engine directory, run these sequence of commands to build the PG engine modified for Babelfish (Github repo: https://github.com/babelfish-for-postgresql/postgresql_modified_for_babelfish):
    ./configure --prefix=$HOME/postgres/ --without-readline --without-zlib --enable-debug CFLAGS="-ggdb" --with-libxml --with-uuid=ossp --with-icu
    make -j 4 2>error.txt
    make install
    make check

3 Also build and install the extensions because uuid-ossp.so is a runtime dependency for babelfish:

    cd contrib && make && sudo make install
4 Install & build dependencies
4.1 Get the latest version of cmake (version 3+ is required)
To get and use the latest version of cmake:
    wget https://github.com/Kitware/CMake/releases/download/v3.20.6/cmake-3.20.6-linux-x86_64.sh
    sh cmake-3.20.6-linux-x86_64.sh
4.2 Install ANTLR
The babelfishpg_tsql contrib has a plug-in parser generated by ANTLR, which depends on cmake and antlr4-cpp-runtime-4.9.3. Unfortunately, there aren't binaries for C++ targets available. You'll also need have uuid-devel installed in order to install antlr4-cpp-runtime-4.9.3.

First copy the jar file in contrib/babelfishpg_tsql/antlr/thirdparty/antlr/ to another location:

cd babelfish_extensions/contrib/babelfishpg_tsql/antlr/thirdparty/antlr/
sudo cp antlr-4.9.3-complete.jar /usr/local/lib

Compile antlr4:
    wget http://www.antlr.org/download/antlr4-cpp-runtime-4.9.3-source.zip
    unzip -d antlr4 antlr4-cpp-runtime-4.9.3-source.zip 
    cd antlr4
    mkdir build && cd build 
    cmake .. -DANTLR_JAR_LOCATION=/usr/local/lib/antlr-4.9.3-complete.jar -DCMAKE_INSTALL_PREFIX=/usr/local -DWITH_DEMO=True
    make
    sudo make install
  Copy libantlr4-runtime to postgres/lib
    cp /usr/local/lib/libantlr4-runtime.so.4.9.3 ~/postgres/lib/

If you come across the error

-- Checking for module 'uuid'
--   No package 'uuid' found
CMake Error at /usr/local/share/cmake-3.21/Modules/FindPkgConfig.cmake:554 (message):
    A required package was not found
Call Stack (most recent call first):
    /usr/local/share/cmake-3.21/Modules/FindPkgConfig.cmake:776 (_pkg_check_modules_internal)
    CMakeLists.txt:44 (pkg_check_modules)
4.3 Check that you have uuid-devel installed. If so, go to antlr4/CMakeLists.txt and comment out the line pkg_check_modules(UUID REQUIRED uuid) by adding a # to the beginning of the line.
More information about installing ANTLR4 can be found at this link.

Set environment variables and paths
    Set the PG_CONFIG environment variable to where you installed the DB engine postgresql_modified_for_babelfish. For example, I installed it under ~/postgres (the default location), so I set PG_CONFIG as follows:

export PG_CONFIG=~/postgres/bin/pg_config

    Set PG_SRC to where the DB engine source package is as we need access to a few engine source files in order to build the Babelfish extensions. For example:

export PG_SRC=~/postgresql_modified_for_babelfish

    Set the cmake environment variable to where you installed cmake (as defined above in step 2). For example:

export cmake=/usr/local/bin/cmake

    Update the file contrib/babelfishpg_tsql/antlr/CMakeLists.txt with the correct antlr4-runtime path (if not there already). For example:

SET (MYDIR /usr/local/include/antlr4-runtime/)

Build the extensions

make and make install each extension within the extension project’s contrib directory:

cd contrib/babelfishpg_money
make && make install
cd ../babelfishpg_common
make && make install
cd ../babelfishpg_tds
make && make install
cd ../babelfishpg_tsql
make && make install

How to install the extensions and how to connect via SQLCMD?

Install the SQL server command line tools by following steps 1 - 3 under Install the SQL Server command-line tools. Use the RHEL7 URL in step 1.
    For convenience, add /opt/mssql-tools/bin/ to your PATH environment variable. This enables you to run the tools without specifying the full path. For Z shell (the default shell for Cloud Desktop), add the following line to your ~/.zshrc file:

export PATH=/opt/mssql-tools/bin:$PATH
From where you installed postgres in the ./configure step adjust the paths of these commands and run them to start the Postgres server:
    ~/postgres/bin/initdb -D ~/postgres/data/
    ~/postgres/bin/pg_ctl -D ~/postgres/data/ -l logfile start
Modify ~/postgres/data/postgresql.conf by uncommenting and adjusting the following 2 properties:
    listen_addresses = '*'
    shared_preload_libraries = 'babelfishpg_tds'
Modify ~/postgres/data/pg_hba.conf to allow connections from allowed IP addresses, replacing 10.x.y.z with your IP address. E.g.
      host    all             all     0.0.0.0/0            md5
Now run this to apply the changes:
    ~/postgres/bin/pg_ctl -D ~/postgres/data/ -l logfile restart

Connect via psql using the command ~/postgres/bin/psql -U your_user_name. Create the extension and set up essential parameters. Please be aware you need to choose either ‘single-db’ or ‘multi-db’ mode during this provisioning step and you CAN NOT change it later. Refer to our documentation page for more information on ‘single-db’ vs ‘multi-db’ mode.

select * from pg_available_extensions WHERE name like 'postgis%'
          babelfishpg_money
 
     babelfishpg_common
 
    babelfishpg_tds
 
      babelfishpg_tsql

    CREATE USER babelfish_user WITH CREATEDB CREATEROLE PASSWORD '12345678' INHERIT;
    DROP DATABASE IF EXISTS babelfish_db;
    CREATE DATABASE babelfish_db OWNER babelfish_user;
    \c babelfish_db
    CREATE EXTENSION IF NOT EXISTS "babelfishpg_tds" CASCADE;
    GRANT ALL ON SCHEMA sys to babelfish_user;
    ALTER SYSTEM SET babelfishpg_tsql.database_name = 'babelfish_db';
    ALTER SYSTEM SET babelfishpg_tds.set_db_session_property = true;
    ALTER DATABASE babelfish_db SET babelfishpg_tsql.migration_mode = 'single-db'|'multi-db';
    SELECT pg_reload_conf();
    CALL SYS.INITIALIZE_BABELFISH('babelfish_user');
    If you run into errors connecting to psql such as psql: error: could not connect to server: No such file or directory try giving permissions by using this command instead:

    sudo ~/postgres/bin/psql -d postgres -U your_user_name

Try connecting to Babelfish via SQLCMD

    sqlcmd -S localhost -U babelfish_user -P 12345678


验证数据库引擎

https://www.modb.pro/db/237005

SELECT @@version,@@servername ;

SELECT * from sysdatabases s;

SELECT * from pg_user;

SELECT * from pg_database;

create database abc

重新连接到 abc库
在 abc库 做如下操作:

create table xxx (id int);
insert into xxx values(1),(2),(3);

SELECT * from xxx;

<think>好的,用户问的是如何在PostgreSQL中导入SQL文件。我需要详细回答这个问题。首先,我应该考虑不同的方法,比如使用psql命令行工具、pgAdmin图形界面,或者通过编程的方式。还要注意不同操作系统下的操作差异,比如Linux和Windows的路径问题。 用户可能已经有一个SQL文件,想要导入到他们的PostgreSQL数据库中。他们可能对命令行不太熟悉,所以需要给出具体的步骤和示例命令。同时,需要提醒他们可能遇到的常见问题,比如权限问题、数据库是否存在、编码问题等。 首先,使用psql命令行工具是最直接的方法。要分步骤说明如何连接到数据库,然后使用\i命令导入文件。还要注意文件路径的正确写法,特别是Windows下路径中的反斜杠需要转义或者用双引号包裹。 其次,pgAdmin是一个图形化工具,适合不习惯命令行的用户。需要指导他们如何在pgAdmin中连接到服务器,选择数据库,然后使用导入功能。可能需要提到导入时的设置选项,比如编码和错误处理。 另外,可能用户的数据量很大,这时候需要考虑性能优化,比如关闭自动提交、调整配置参数等。这部分可以作为高级选项提到,但可能不是所有用户都需要。 还要注意权限问题,确保用户有权限访问目标数据库和模式。如果SQL文件中有创建用户的语句,可能需要管理员权限,这时候需要提醒用户使用超级用户登录。 常见问题部分要涵盖文件路径错误、权限不足、编码不匹配、SQL语法错误等。例如,用户可能遇到无法找到文件的问题,这时候需要检查路径是否正确,或者是否在正确的目录下运行命令。 最后,相关问题应该覆盖不同的场景,比如导入到远程数据库、处理大文件、验证数据完整性等。这样用户可以根据自己的需求进一步了解相关信息。</think>在 PostgreSQL 中导入 SQL 文件可以通过多种方式实现,以下是常见的方法及注意事项: --- ### **1. 使用 `psql` 命令行工具** 这是最直接的方式,适用于本地或远程数据库。 #### **步骤** ```bash # 连接到目标数据库并执行 SQL 文件 psql -h 主机地址 -p 端口 -U 用户名 -d 数据库-f 文件路径.sql ``` #### **示例** ```bash # 本地导入(默认主机为 localhost,端口 5432) psql -U postgres -d mydb -f /path/to/backup.sql # 远程导入(假设主机为 192.168.1.100) psql -h 192.168.1.100 -U postgres -d mydb -f /path/to/backup.sql ``` #### **注意事项** - **权限**:确保执行用户有目标数据库的写权限。 - **路径**:文件路径需为 PostgreSQL 服务器可访问的路径(本地或网络共享)。 - **编码**:SQL 文件的编码需与数据库编码一致(如 UTF8)。 - **模式**:若 SQL 文件包含 `CREATE SCHEMA`,需确保目标模式不存在冲突。 --- ### **2. 使用 `\i` 命令在 `psql` 交互模式中导入** 适合需要分步执行或调试的场景。 #### **步骤** ```sql -- 进入 psql 交互模式 psql -U postgres -d mydb -- 在 psql 中执行导入命令 \i /path/to/backup.sql ``` --- ### **3. 使用 `pgAdmin` 图形化工具** 适合不熟悉命令行的用户。 #### **步骤** 1. 打开 pgAdmin,连接到目标数据库2. 右键点击数据库 → **Query Tool**。 3. 在查询窗口中点击 **Open File**(或快捷键 `Ctrl+O`),选择 SQL 文件。 4. 点击 **Execute**(或 `F5`)运行文件。 #### **注意事项** - **文件大小**:pgAdmin 对大文件(如超过 1GB)效率较低,建议使用命令行。 - **日志输出**:可在查询窗口下方查看执行日志。 --- ### **4. 通过编程方式导入(Python 示例)** 使用 `psycopg2` 库执行 SQL 文件内容。 ```python import psycopg2 # 连接数据库 conn = psycopg2.connect( host="localhost", database="mydb", user="postgres", password="password" ) # 读取 SQL 文件 with open('/path/to/backup.sql', 'r') as f: sql = f.read() # 执行 SQL cur = conn.cursor() cur.execute(sql) conn.commit() cur.close() ``` --- ### **5. 使用 `COPY` 命令导入数据文件** 若 SQL 文件仅包含数据(如 `COPY` 命令),需确保数据文件路径可访问。 ```sql -- 示例:从 CSV 文件导入数据到表 COPY my_table FROM '/path/to/data.csv' DELIMITER ',' CSV HEADER; ``` --- ### **常见问题排查** 1. **权限不足** - 错误提示:`ERROR: permission denied for schema public` - 解决方案:使用超级用户(如 `postgres`)执行,或授予权限: ```sql GRANT ALL PRIVILEGES ON DATABASE mydb TO myuser; ``` 2. **文件路径错误** - 确保文件路径正确且 PostgreSQL 有权限访问。 - 在 Windows 下,路径需使用双反斜杠 `\\` 或正斜杠 `/`: ```bash psql -f "C:\\backup\\data.sql" ``` 3. **编码不匹配** - 若导入时提示 `invalid byte sequence for encoding "UTF8"`,需转换文件编码: ```bash iconv -f GBK -t UTF-8 input.sql -o output.sql ``` 4. **SQL 语法错误** - 检查 SQL 文件是否包含与当前 PostgreSQL 版本不兼容的语法。 --- ### **高级技巧** - **分批导入大文件** 使用 `split` 命令将大文件拆分后导入: ```bash split -l 1000000 backup.sql part_ # 每 100 万行拆分一次 for file in part_*; do psql -d mydb -f "$file"; done ``` - **忽略错误继续执行** 在 SQL 文件开头添加 `SET LOCAL statement_timeout = '30s';` 避免超时中断。 ---
评论 6
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值