DBFSync Guía de bolsilloPocket Guide
GitHub

DBF de Visual FoxPro a PostgreSQL, SQL Server o SQLite Visual FoxPro DBFs to PostgreSQL, SQL Server or SQLite

Todos los comandos de dbfsync en una página. El ERP Xbase++ sigue operando sobre sus DBF mientras otros servicios consumen una base relacional actualizada.

Every dbfsync command on one page. The Xbase++ ERP keeps operating on its DBFs while other services consume an up-to-date relational database.

.dbfODBC x86RECNO()+SHA-256 STAGINGBEGIN … COMMITSQL
Windows win-x86. El proceso debe ser de 32 bits porque el Microsoft Visual FoxPro ODBC Driver es x86. Windows win-x86. The process must be 32-bit because the Microsoft Visual FoxPro ODBC Driver is x86.
01

InstalaciónInstall

Compile desde el código fuente con el SDK de .NET 10. El binario resultante se llama dbfsync.exe.

Build from source with the .NET 10 SDK. The resulting binary is called dbfsync.exe.

CompilarBuild

git clone https://github.com/peopleworks/DBFSync.git
cd DBFSync
dotnet publish src/DBFSync/DBFSync.csproj `
  --configuration Release `
  --runtime win-x86 `
  --self-contained false `
  --output dist/win-x86

CI también publica este artefacto en cada push: descárguelo desde la pestaña Actions.

CI publishes this artifact on every push too — download it from the Actions tab.

RequisitosRequirements

Windows
x86 o x64 (proceso de 32 bits)x86 or x64 (32-bit process)
ODBC
Microsoft Visual FoxPro ODBC Driver (x86)Microsoft Visual FoxPro ODBC Driver (x86)
.NET 10
Runtime en destino, SDK para compilarRuntime on target, SDK to build
# verificar instalaciónverify install
dbfsync --version
dbfsync --help
dbfsync sample
02

Inicio rápido con SQLiteSQLite quick start

SQLite no requiere servidor ni credenciales: es el destino recomendado para la primera prueba. El archivo y sus carpetas padre se crean solos.

SQLite needs no server and no credentials — the recommended destination for a first run. The file and its parent folders are created automatically.

# 1 · crear el perfil y el archivo SQLitecreate the profile and the SQLite file
dbfsync profile set local `
  --engine sqlite `
  --file C:\DBFSync\erp.db

# 2 · revisar qué se leeráreview what will be read
dbfsync inspect `
  --source C:\ERP\Datos `
  --tables "clientes,articulos,fa*.dbf" `
  --exclude "*hist*,*bak*"

# 3 · carga inicialinitial load
dbfsync migrate `
  --profile local `
  --source C:\ERP\Datos `
  --tables "clientes,articulos,fa*.dbf"

# 4 · sincronizaciones posterioressubsequent synchronizations
dbfsync sync `
  --profile local `
  --source C:\ERP\Datos `
  --tables "clientes,articulos,fa*.dbf" `
  --sync-schema
03

Perfiles y seguridadProfiles and security

Un perfil guarda motor, servidor, base, esquema y usuario. La contraseña se protege con DPAPI y nunca viaja en los argumentos.

A profile stores engine, server, database, schema, and user. The password is protected with DPAPI and never travels in the arguments.

PostgreSQL SSL verificadoverified SSL

dbfsync profile set erp-pg `
  --engine postgresql `
  --server pg01.example.com `
  --port 5432 `
  --database erp `
  --schema public `
  --user dbfsync `
  --create-database

SQL Server autenticación WindowsWindows authentication

dbfsync profile set erp-mssql `
  --engine sqlserver `
  --server sql01 `
  --database ERP `
  --schema dbo `
  --integrated

AdministrarManage

dbfsync profile list
dbfsync profile show erp-pg
dbfsync profile test erp-pg
dbfsync profile remove erp-pg

show nunca imprime la contraseña.

show never prints the password.

Contraseña desatendidaUnattended password

# lee una línea desde stdinreads one line from stdin
"s3cr3t" | dbfsync profile set erp-pg `
  --engine postgresql `
  --server pg01.example.com `
  --database erp `
  --user dbfsync `
  --password-stdin

Opciones de profile setprofile set options

OpciónOption MotoresEngines DescripciónDescription
--enginepg · mssql · sqliteRequerido: postgresql, sqlserver o sqliteRequired: postgresql, sqlserver, or sqlite
--serverpg · mssqlServidor o dirección IPServer or IP address
--portpg · mssqlPuerto; PostgreSQL usa 5432 si se omitePort; PostgreSQL uses 5432 when omitted
--databasepg · mssqlBase de datosDatabase
--filesqliteArchivo de base SQLiteSQLite database file
--schemapg · mssqlPredeterminado public o dboDefaults to public or dbo
--userpg · mssqlUsuario cuando no se usa autenticación integradaUser when integrated authentication is not used
--integratedmssqlUsa la identidad Windows del procesoUses the process Windows identity
--scopepg · mssqlÁmbito DPAPI user o machine; predeterminado userDPAPI scope user or machine; defaults to user
--no-encryptpg · mssqlDesactiva SSL / deja de exigir cifrado. Solo desarrollo local confiableDisables SSL / stops requiring encryption. Trusted local development only
--trust-server-certificatepg · mssqlMantiene el cifrado sin validar el certificadoKeeps encryption without validating the certificate
--password-stdinpg · mssqlLee una línea desde stdin en vez de preguntarReads one line from stdin instead of prompting
--create-databasetodosallCrea la base o el archivo si no existeCreates the database or file when missing
--no-encrypt desactiva la protección del transporte. Úselo únicamente contra un servidor local de confianza, nunca sobre una red compartida. --no-encrypt turns off transport protection. Use it only against a trusted local server, never over a shared network.
04

Crear la baseCreate the database

Crea o verifica la base del perfil. Idempotente: si ya existe, lo informa y termina con éxito.

Creates or verifies the profile database. Idempotent: if it already exists it reports so and exits successfully.

dbfsync database create --profile erp-pg

# aliases equivalentesequivalent aliases
dbfsync db ensure --profile erp-pg
dbfsync base crear --profile erp-pg

--profile es la única opción aceptada por este comando.

--profile is the only option this command accepts.

05

Inspeccionar antes de escribirInspect before writing

Muestra esquema, filas activas y una muestra de datos sin tocar el destino. No necesita perfil.

Shows schema, live rows, and a data sample without touching the destination. No profile needed.

dbfsync inspect `
  --source C:\ERP\Datos `
  --tables "fa*.dbf" `
  --exclude "*hist*"

# toda la carpetathe whole folder
dbfsync inspect --source C:\ERP\Datos --all
inspect solo acepta --source, --tables, --table, --exclude y --all. Es de solo lectura. inspect accepts only --source, --tables, --table, --exclude, and --all. It is read-only.
06

Migrar y sincronizarMigrate and synchronize

Ambos comparten las mismas opciones. La diferencia está en qué hacen con el contenido que ya existe en el destino.

Both share the same options. The difference is what they do with content that already exists in the destination.

migrate carga inicialinitial load

Reemplaza el contenido del destino. Es el punto de partida de una tabla.

Replaces the destination content. It is a table's starting point.

dbfsync migrate `
  --profile erp-pg `
  --source C:\ERP\Datos `
  --tables "clientes,articulos" `
  --batch-size 5000

sync reconciliaciónreconciliation

Inserta nuevos, actualiza cuando cambia el SHA-256 y elimina los ausentes o marcados como borrados.

Inserts new rows, updates when the SHA-256 changes, and deletes rows that are absent or flagged as deleted.

dbfsync sync `
  --profile erp-pg `
  --source C:\ERP\Datos `
  --tables "clientes,articulos" `
  --sync-schema

Opciones de transferenciaTransfer options

OpciónOption DescripciónDescription
--profilePerfil destino. RequeridoDestination profile. Required
--sourceCarpeta con los DBF. RequeridoFolder holding the DBFs. Required
--tablesNombres o patrones separados por comaComma-separated names or patterns
--tablePatrón individual; puede repetirseSingle pattern; may be repeated
--allTodos los DBF de la carpetaEvery DBF in the folder
--excludeExcluye nombres o patronesExcludes names or patterns
--batch-sizeFilas por lote; predeterminado 5000, rango 1–100000Rows per batch; defaults to 5000, range 1–100000
--sync-schemaAplica evolución estructural seguraApplies safe structural evolution
--allow-drop-columnsAutoriza eliminar columnas; exige --sync-schemaAuthorizes dropping columns; requires --sync-schema
--recreateReconstruye las tablas; solo migrateRebuilds the tables; migrate only
07

Selección de DBFDBF selection

Los patrones usan * y ?. La extensión .dbf es opcional y las exclusiones se aplican al final.

Patterns use * and ?. The .dbf extension is optional and exclusions are applied last.

Formas de seleccionarWays to select

# lista separada por comacomma-separated list
--tables "clientes,articulos,fa*.dbf"

# opción repetidarepeated option
--table "fa*" --table "cbmovf??"

# toda la carpeta menos lo excluidowhole folder minus exclusions
--all --exclude "*hist*,*bak*,tmp?"

ComodinesWildcards

*
Cualquier cantidad de caracteresAny number of characters
?
Exactamente un carácterExactly one character
fa*.dbf
Todo lo que empieza con faEverything starting with fa
cbmovf??
cbmovf + dos caracterescbmovf + two characters
--all y los patrones de inclusión son mutuamente excluyentes. --all and inclusion patterns are mutually exclusive.
08

Evolución del esquemaSchema evolution

Sin --sync-schema, una diferencia estructural detiene la tabla en vez de adivinar. Los cambios destructivos exigen autorización explícita.

Without --sync-schema, a structural difference stops the table instead of guessing. Destructive changes require explicit authorization.

SeguroSafe

Agrega campos nuevos y amplía tipos compatibles.

Adds new fields and widens compatible types.

dbfsync sync `
  --profile erp-pg `
  --source C:\ERP\Datos `
  --all `
  --sync-schema

DestructivoDestructive

Eliminar columnas o reconstruir la tabla borra datos del destino.

Dropping columns or rebuilding the table deletes destination data.

# eliminar columnas ausentes en el DBFdrop columns missing from the DBF
dbfsync sync--sync-schema --allow-drop-columns

# reconstruir desde cero (solo migrate)rebuild from scratch (migrate only)
dbfsync migrate--recreate
--allow-drop-columns exige --sync-schema. Ninguna de las dos es reversible. --allow-drop-columns requires --sync-schema. Neither one is reversible.
09

AutomatizaciónAutomation

La tarea programada solo recibe el nombre del perfil: nunca necesita la contraseña.

The scheduled task only receives the profile name — it never needs the password.

Task Scheduler

$action = New-ScheduledTaskAction `
  -Execute "C:\Tools\PeopleWorks\DBFSync\dbfsync.exe" `
  -Argument 'sync --profile erp-pg --source C:\ERP\Datos --tables "fa*.dbf" --lang es'

$trigger = New-ScheduledTaskTrigger -Once `
  -At (Get-Date).AddMinutes(1) `
  -RepetitionInterval (New-TimeSpan -Minutes 5)

$settings = New-ScheduledTaskSettingsSet `
  -MultipleInstances IgnoreNew -StartWhenAvailable

Register-ScheduledTask -TaskName "PeopleWorks DBFSync ERP" `
  -Action $action -Trigger $trigger -Settings $settings
Con --scope user la tarea debe correr con la misma cuenta que creó el perfil. Con --scope machine, limite el acceso NTFS a la carpeta de configuración. With --scope user the task must run under the same account that created the profile. With --scope machine, restrict NTFS access to the configuration folder.

Códigos de salidaExit codes

0Ejecución correctaSuccessful run
1Argumentos inválidos, error de conexión o transferenciaInvalid arguments, connection or transfer error
130Cancelación con Ctrl+CCancelled with Ctrl+C

Trate únicamente el 0 como éxito.

Treat only 0 as success.

Rutas y variablesPaths and variables

DBFSYNC_LANG
Idioma de la CLI (es / en)CLI language (es / en)
DBFSYNC_HOME
Carpeta de configuración y logsConfiguration and log folder
# predeterminadosdefaults
C:\ProgramData\PeopleWorks\DBFSync\profiles.json
C:\ProgramData\PeopleWorks\DBFSync\logs\

# idioma sin argumentoslanguage without arguments
$env:DBFSYNC_LANG = "es"

Los logs registran progreso, conteos y errores, pero nunca contraseñas.

Logs record progress, counts, and errors, but never passwords.

10

ChuletaCheat sheet

Todos los comandos y sus aliases. --lang (o --language) puede aparecer en cualquier posición.

Every command and its aliases. --lang (or --language) can appear at any position.

ComandoCommand Aliases Qué haceWhat it does
dbfsync --help-h · help · ayudaAyuda resumidaSummary help
dbfsync --version-v · versionVersiónVersion
dbfsync samplesamples · example · ejemplo(s)Escenarios completosFull scenarios
profile set NAMEperfil guardarCrea o reemplaza un perfilCreates or replaces a profile
profile listperfil listarLista perfilesLists profiles
profile show NAMEperfil mostrarMuestra un perfil sin secretosShows a profile without secrets
profile test NAMEperfil probarPrueba la conexiónTests the connection
profile remove NAMEdelete · perfil eliminarElimina un perfilRemoves a profile
database createdb · base · ensure · crear · asegurarCrea o verifica la baseCreates or verifies the database
inspectinspeccionarEsquema, filas activas y muestraSchema, live rows, and sample
migratemigrarReemplaza el contenido destinoReplaces destination content
syncsynchronize · sincronizarReconcilia altas, cambios y bajasReconciles inserts, updates, and deletes