Coverage Report

Created: 2026-01-13 10:09

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/mdbtools/src/libmdb/backend.c
Line
Count
Source
1
/* MDB Tools - A library for reading MS Access database files
2
 * Copyright (C) 2000-2011 Brian Bruns and others
3
 *
4
 * This library is free software; you can redistribute it and/or
5
 * modify it under the terms of the GNU Library General Public
6
 * License as published by the Free Software Foundation; either
7
 * version 2 of the License, or (at your option) any later version.
8
 *
9
 * This library is distributed in the hope that it will be useful,
10
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
12
 * Library General Public License for more details.
13
 *
14
 * You should have received a copy of the GNU Library General Public
15
 * License along with this library; if not, write to the Free Software
16
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA
17
 */
18
19
/*
20
** functions to deal with different backend database engines
21
*/
22
23
#include "mdbtools.h"
24
#include "mdbprivate.h"
25
26
/*    Access data types */
27
static const MdbBackendType mdb_access_types[] = {
28
    [MDB_BOOL] = { .name = "Boolean" },
29
    [MDB_BYTE] = { .name = "Byte" },
30
    [MDB_INT] = { .name = "Integer" },
31
    [MDB_LONGINT] = { .name = "Long Integer" },
32
    [MDB_MONEY] = { .name = "Currency" },
33
    [MDB_FLOAT] = { .name = "Single" },
34
    [MDB_DOUBLE] = { .name = "Double" },
35
    [MDB_DATETIME] = { .name = "DateTime" },
36
    [MDB_BINARY] = { .name = "Binary" },
37
    [MDB_TEXT] = { .name = "Text", .needs_char_length = 1 },
38
    [MDB_OLE] = { .name = "OLE", .needs_byte_length = 1 },
39
    [MDB_MEMO] = { .name = "Memo/Hyperlink", .needs_char_length = 1 },
40
    [MDB_REPID] = { .name = "Replication ID" },
41
    [MDB_NUMERIC] = { .name = "Numeric", .needs_precision = 1, .needs_scale = 1 },
42
};
43
44
/*    Oracle data types */
45
static const MdbBackendType mdb_oracle_types[] = {
46
    [MDB_BOOL] = { .name = "NUMBER(1)" },
47
    [MDB_BYTE] = { .name = "NUMBER(3)" },
48
    [MDB_INT] = { .name = "NUMBER(5)" },
49
    [MDB_LONGINT] = { .name = "NUMBER(11)" },
50
    [MDB_MONEY] = { .name = "NUMBER(15,2)" },
51
    [MDB_FLOAT] = { .name = "FLOAT" },
52
    [MDB_DOUBLE] = { .name = "FLOAT" },
53
    [MDB_DATETIME] = { .name = "TIMESTAMP" },
54
    [MDB_BINARY] = { .name = "BINARY" },
55
    [MDB_TEXT] = { .name = "VARCHAR2", .needs_char_length= 1 },
56
    [MDB_OLE] = { .name = "BLOB" },
57
    [MDB_MEMO] = { .name = "CLOB" },
58
    [MDB_REPID] = { .name = "NUMBER", .needs_precision = 1 },
59
    [MDB_NUMERIC] = { .name = "NUMBER", .needs_precision = 1 },
60
};
61
static const MdbBackendType mdb_oracle_shortdate_type =
62
        { .name = "DATE" };
63
64
/*    Sybase/MSSQL data types */
65
static const MdbBackendType mdb_sybase_types[] = {
66
    [MDB_BOOL] = { .name = "bit" },
67
    [MDB_BYTE] = { .name = "char", .needs_byte_length = 1 },
68
    [MDB_INT] = { .name = "smallint" },
69
    [MDB_LONGINT] = { .name = "int" },
70
    [MDB_MONEY] = { .name = "money" },
71
    [MDB_FLOAT] = { .name = "real" },
72
    [MDB_DOUBLE] = { .name = "float" },
73
    [MDB_DATETIME] = { .name = "smalldatetime" },
74
    [MDB_BINARY] = { .name = "varbinary", .needs_byte_length = 1 },
75
    [MDB_TEXT] = { .name = "nvarchar", .needs_char_length = 1 },
76
    [MDB_OLE] = { .name = "varbinary(max)" },
77
    [MDB_MEMO] = { .name = "nvarchar(max)" },
78
    [MDB_REPID] = { .name = "Sybase_Replication ID" },
79
    [MDB_NUMERIC] = { .name = "numeric", .needs_precision = 1, .needs_scale = 1 },
80
};
81
static const MdbBackendType mdb_sybase_shortdate_type =
82
        { .name = "DATE" };
83
84
/*    Postgres data types */
85
static const MdbBackendType mdb_postgres_types[] = {
86
    [MDB_BOOL] = { .name = "BOOLEAN" },
87
    [MDB_BYTE] = { .name = "SMALLINT" },
88
    [MDB_INT] = { .name = "INTEGER" },
89
    [MDB_LONGINT] = { .name = "INTEGER" }, /* bigint */
90
    [MDB_MONEY] = { .name = "NUMERIC(15,2)" }, /* money deprecated ? */
91
    [MDB_FLOAT] = { .name = "REAL" },
92
    [MDB_DOUBLE] = { .name = "DOUBLE PRECISION" },
93
    [MDB_DATETIME] = { .name = "TIMESTAMP WITHOUT TIME ZONE" },
94
    [MDB_BINARY] = { .name = "BYTEA" },
95
    [MDB_TEXT] = { .name = "VARCHAR", .needs_char_length = 1 },
96
    [MDB_OLE] = { .name = "BYTEA" },
97
    [MDB_MEMO] = { .name = "TEXT" },
98
    [MDB_REPID] = { .name = "UUID" },
99
    [MDB_NUMERIC] = { .name = "NUMERIC", .needs_precision = 1, .needs_scale = 1 },
100
};
101
static const MdbBackendType mdb_postgres_shortdate_type =
102
        { .name = "DATE" };
103
static const MdbBackendType mdb_postgres_serial_type =
104
        { .name = "SERIAL" };
105
106
/*    MySQL data types */
107
static const MdbBackendType mdb_mysql_types[] = {
108
    [MDB_BOOL] = { .name = "boolean" },
109
    [MDB_BYTE] = { .name = "tinyint" },
110
    [MDB_INT] = { .name = "smallint" },
111
    [MDB_LONGINT] = { .name = "int" },
112
    [MDB_MONEY] = { .name = "float" },
113
    [MDB_FLOAT] = { .name = "float" },
114
    [MDB_DOUBLE] = { .name = "double" },
115
    [MDB_DATETIME] = { .name = "datetime" },
116
    [MDB_BINARY] = { .name = "blob" },
117
    [MDB_TEXT] = { .name = "varchar", .needs_char_length = 1 },
118
    [MDB_OLE] = { .name = "blob" },
119
    [MDB_MEMO] = { .name = "text" },
120
    [MDB_REPID] = { .name = "char(38)" },
121
    [MDB_NUMERIC] = { .name = "numeric", .needs_precision = 1, .needs_scale = 1 },
122
};
123
static const MdbBackendType mdb_mysql_shortdate_type =
124
        { .name = "date" };
125
/* We can't use the MySQL SERIAL type because that uses a bigint which
126
 * is 64 bits wide, whereas MDB long ints are 32 bits */
127
static const MdbBackendType mdb_mysql_serial_type =
128
        { .name = "int not null auto_increment unique" };
129
130
/*    sqlite data types */
131
static const MdbBackendType mdb_sqlite_types[] = {
132
    [MDB_BOOL] = { .name = "INTEGER" },
133
    [MDB_BYTE] = { .name = "INTEGER" },
134
    [MDB_INT] = { .name = "INTEGER" },
135
    [MDB_LONGINT] = { .name = "INTEGER" },
136
    [MDB_MONEY] = { .name = "REAL" },
137
    [MDB_FLOAT] = { .name = "REAL" },
138
    [MDB_DOUBLE] = { .name = "REAL" },
139
    [MDB_DATETIME] = { .name = "DateTime" },
140
    [MDB_BINARY] = { .name = "BLOB" },
141
    [MDB_TEXT] = { .name = "varchar" },
142
    [MDB_OLE] = { .name = "BLOB" },
143
    [MDB_MEMO] = { .name = "TEXT" },
144
    [MDB_REPID] = { .name = "INTEGER" },
145
    [MDB_NUMERIC] = { .name = "INTEGER" },
146
};
147
148
enum {
149
  MDB_BACKEND_ACCESS = 1,
150
  MDB_BACKEND_ORACLE,
151
  MDB_BACKEND_SYBASE,
152
  MDB_BACKEND_POSTGRES,
153
  MDB_BACKEND_MYSQL,
154
  MDB_BACKEND_SQLITE,
155
};
156
157
static void mdb_drop_backend(gpointer key, gpointer value, gpointer data);
158
159
160
0
static gchar *passthrough_unchanged(const gchar *str) {
161
0
    return (gchar *)str;
162
0
}
163
164
0
static gchar *to_lower_case(const gchar *str) {
165
0
    return g_utf8_strdown(str, -1);
166
0
}
167
168
/**
169
 * Convenience function to replace an input string with its database specific normalised version.
170
 *
171
 * This function throws away the input string after normalisation, freeing its memory, and replaces it with a new
172
 * normalised version allocated on the stack.
173
 *
174
 * @param mdb  Database specific MDB handle containing pointers to utility methods
175
 * @param str string to normalise
176
 * @return a pointer to the normalised version of the input string
177
 */
178
0
gchar *mdb_normalise_and_replace(MdbHandle *mdb, gchar **str) {
179
0
    gchar *normalised_str = mdb->default_backend->normalise_case(*str);
180
0
    if (normalised_str != *str) {
181
        /* Free and replace the old string only and only if a new string was created at a different memory location
182
         * so that we can account for the case where strings a just passed through unchanged.
183
         */
184
0
        free(*str);
185
0
        *str = normalised_str;
186
0
    }
187
0
    return *str;
188
0
}
189
190
static gchar*
191
0
quote_generic(const gchar *value, gchar quote_char, gchar escape_char) {
192
0
  gchar *result, *pr;
193
0
  unsigned char c;
194
195
0
  pr = result = g_malloc(1+4*strlen(value)+2); // worst case scenario
196
197
0
  *pr++ = quote_char;
198
0
  while ((c=*(unsigned char*)value++)) {
199
0
    if (c<32) {
200
0
      sprintf(pr, "\\%03o", c);
201
0
      pr+=4;
202
0
      continue;
203
0
    }
204
0
    else if (c == quote_char) {
205
0
      *pr++ = escape_char;
206
0
    }
207
0
    *pr++ = c;
208
0
  }
209
0
  *pr++ = quote_char;
210
0
  *pr++ = '\0';
211
0
  return result;
212
0
}
213
static gchar*
214
0
quote_schema_name_bracket_merge(const gchar* schema, const gchar *name) {
215
0
  if (schema)
216
0
    return g_strconcat("[", schema, "_", name, "]", NULL);
217
0
  else
218
0
    return g_strconcat("[", name, "]", NULL);
219
0
}
220
221
/*
222
 * For backends that really does support schema
223
 * returns "name" or "schema"."name"
224
 */
225
static gchar*
226
quote_schema_name_dquote(const gchar* schema, const gchar *name)
227
0
{
228
0
  if (schema) {
229
0
    gchar *frag1 = quote_generic(schema, '"', '"');
230
0
    gchar *frag2 = quote_generic(name, '"', '"');
231
0
    gchar *result = g_strconcat(frag1, ".", frag2, NULL);
232
0
    g_free(frag1);
233
0
    g_free(frag2);
234
0
    return result;
235
0
  }
236
0
  return quote_generic(name, '"', '"');
237
0
}
238
239
/*
240
 * For backends that really do NOT support schema
241
 * returns "name" or "schema_name"
242
 */
243
/*
244
static gchar*
245
quote_schema_name_dquote_merge(const gchar* schema, const gchar *name)
246
{
247
  if (schema) {
248
    gchar *combined = g_strconcat(schema, "_", name, NULL);
249
    gchar *result = quote_generic(combined, '"', '"');
250
    g_free(combined);
251
    return result;
252
  }
253
  return quote_generic(name, '"', '"');
254
}*/
255
256
static gchar*
257
quote_schema_name_rquotes_merge(const gchar* schema, const gchar *name)
258
0
{
259
0
  if (schema) {
260
0
    gchar *combined = g_strconcat(schema, "_", name, NULL);
261
0
    gchar *result = quote_generic(combined, '`', '`');
262
0
    g_free(combined);
263
0
    return result;
264
0
  }
265
0
  return quote_generic(name, '`', '`');
266
0
}
267
268
static gchar*
269
quote_with_squotes(const gchar* value)
270
0
{
271
0
  return quote_generic(value, '\'', '\'');
272
0
}
273
274
const MdbBackendType*
275
0
mdb_get_colbacktype(const MdbColumn *col) {
276
0
  MdbBackend *backend = col->table->entry->mdb->default_backend;
277
0
  int col_type = col->col_type;
278
0
  if (col_type > MDB_NUMERIC)
279
0
    return NULL;
280
0
  if (col_type == MDB_LONGINT && col->is_long_auto && backend->type_autonum)
281
0
    return backend->type_autonum;
282
0
  if (col_type == MDB_DATETIME && backend->type_shortdate) {
283
0
    if (mdb_col_is_shortdate(col))
284
0
      return backend->type_shortdate;
285
0
  }
286
0
  if (!backend->types_table[col_type].name[0])
287
0
    return NULL;
288
0
  return &backend->types_table[col_type];
289
0
}
290
291
const char *
292
mdb_get_colbacktype_string(const MdbColumn *col)
293
0
{
294
0
  const MdbBackendType *type = mdb_get_colbacktype(col);
295
0
  if (!type) {
296
      // return NULL;
297
0
    static TLS char buf[16];
298
0
    snprintf(buf, sizeof(buf), "Unknown_%04x", col->col_type);
299
0
    return buf;
300
0
  }
301
0
  return type->name;
302
0
}
303
int
304
mdb_colbacktype_takes_length(const MdbColumn *col)
305
0
{
306
0
  const MdbBackendType *type = mdb_get_colbacktype(col);
307
0
  if (!type) return 0;
308
0
  return type->needs_precision || type->needs_char_length || type->needs_byte_length;
309
0
}
310
static int
311
mdb_colbacktype_takes_length_in_characters(const MdbColumn *col)
312
0
{
313
0
  const MdbBackendType *type = mdb_get_colbacktype(col);
314
0
  if (!type) return 0;
315
0
  return type->needs_char_length;
316
0
}
317
318
/**
319
 * mdb_init_backends
320
 *
321
 * Initializes the mdb_backends hash and loads the builtin backends.
322
 * Use mdb_remove_backends() to destroy this hash when done.
323
 */
324
void mdb_init_backends(MdbHandle *mdb)
325
338
{
326
338
    if (mdb->backends) {
327
0
        mdb_remove_backends(mdb);
328
0
    }
329
338
  mdb->backends = g_hash_table_new(g_str_hash, g_str_equal);
330
331
338
  mdb_register_backend(mdb, "access",
332
338
    MDB_SHEXP_DROPTABLE|MDB_SHEXP_CST_NOTNULL|MDB_SHEXP_DEFVALUES,
333
338
    mdb_access_types, NULL, NULL,
334
338
    "Date()", "Date()",
335
338
    NULL,
336
338
    NULL,
337
338
    "-- That file uses encoding %s\n",
338
338
    "DROP TABLE %s;\n",
339
338
    NULL,
340
338
    NULL,
341
338
    NULL,
342
338
    NULL,
343
338
    NULL,
344
338
    quote_schema_name_bracket_merge);
345
338
  mdb_register_backend(mdb, "sybase",
346
338
    MDB_SHEXP_DROPTABLE|MDB_SHEXP_CST_NOTNULL|MDB_SHEXP_CST_NOTEMPTY|MDB_SHEXP_COMMENTS|MDB_SHEXP_DEFVALUES,
347
338
    mdb_sybase_types, &mdb_sybase_shortdate_type, NULL,
348
338
    "getdate()", "getdate()",
349
338
    NULL,
350
338
    NULL,
351
338
    "-- That file uses encoding %s\n",
352
338
    "DROP TABLE %s;\n",
353
338
    "ALTER TABLE %s ADD CHECK (%s <>'');\n",
354
338
    "COMMENT ON COLUMN %s.%s IS %s;\n",
355
338
    NULL,
356
338
    "COMMENT ON TABLE %s IS %s;\n",
357
338
    NULL,
358
338
    quote_schema_name_dquote);
359
338
  mdb_register_backend(mdb, "oracle",
360
338
    MDB_SHEXP_DROPTABLE|MDB_SHEXP_CST_NOTNULL|MDB_SHEXP_COMMENTS|MDB_SHEXP_INDEXES|MDB_SHEXP_RELATIONS|MDB_SHEXP_DEFVALUES,
361
338
    mdb_oracle_types, &mdb_oracle_shortdate_type, NULL,
362
338
    "current_date", "sysdate",
363
338
    NULL,
364
338
    NULL,
365
338
    "-- That file uses encoding %s\n",
366
338
    "DROP TABLE %s;\n",
367
338
    NULL,
368
338
    "COMMENT ON COLUMN %s.%s IS %s;\n",
369
338
    NULL,
370
338
    "COMMENT ON TABLE %s IS %s;\n",
371
338
    NULL,
372
338
    quote_schema_name_dquote);
373
338
  mdbi_register_backend2(mdb, "postgres",
374
338
    MDB_SHEXP_DROPTABLE|MDB_SHEXP_CST_NOTNULL|MDB_SHEXP_CST_NOTEMPTY|MDB_SHEXP_COMMENTS|MDB_SHEXP_INDEXES|MDB_SHEXP_RELATIONS|MDB_SHEXP_DEFVALUES|MDB_SHEXP_BULK_INSERT,
375
338
    mdb_postgres_types, &mdb_postgres_shortdate_type, &mdb_postgres_serial_type,
376
338
    "current_date", "now()",
377
338
    "%Y-%m-%d %H:%M:%S",
378
338
    "%Y-%m-%d",
379
338
    "SET client_encoding = '%s';\n",
380
338
        "CREATE TABLE IF NOT EXISTS %s\n",
381
338
    "DROP TABLE IF EXISTS %s;\n",
382
338
    "ALTER TABLE %s ADD CHECK (%s <>'');\n",
383
338
    "COMMENT ON COLUMN %s.%s IS %s;\n",
384
338
    NULL,
385
338
    "COMMENT ON TABLE %s IS %s;\n",
386
338
    NULL,
387
338
    quote_schema_name_dquote,
388
338
        to_lower_case);
389
338
  mdb_register_backend(mdb, "mysql",
390
338
    MDB_SHEXP_DROPTABLE|MDB_SHEXP_CST_NOTNULL|MDB_SHEXP_CST_NOTEMPTY|MDB_SHEXP_INDEXES|MDB_SHEXP_RELATIONS|MDB_SHEXP_DEFVALUES|MDB_SHEXP_BULK_INSERT,
391
338
    mdb_mysql_types, &mdb_mysql_shortdate_type, &mdb_mysql_serial_type,
392
338
    "current_date", "now()",
393
338
    "%Y-%m-%d %H:%M:%S",
394
338
    "%Y-%m-%d",
395
338
    "-- That file uses encoding %s\n",
396
338
    "DROP TABLE IF EXISTS %s;\n",
397
338
    "ALTER TABLE %s ADD CHECK (%s <>'');\n",
398
338
    NULL,
399
338
    "COMMENT %s",
400
338
    NULL,
401
338
    "COMMENT %s",
402
338
    quote_schema_name_rquotes_merge);
403
338
  mdb_register_backend(mdb, "sqlite",
404
338
    MDB_SHEXP_DROPTABLE|MDB_SHEXP_DEFVALUES|MDB_SHEXP_BULK_INSERT|MDB_SHEXP_INDEXES|MDB_SHEXP_CST_NOTNULL,
405
338
    mdb_sqlite_types, NULL, NULL,
406
338
    "date('now')", "date('now')",
407
338
    "%Y-%m-%d %H:%M:%S",
408
338
    "%Y-%m-%d",
409
338
    "-- That file uses encoding %s\n",
410
338
    "DROP TABLE IF EXISTS %s;\n",
411
338
    NULL,
412
338
    NULL,
413
338
    NULL,
414
338
    NULL,
415
338
    NULL,
416
338
    quote_schema_name_rquotes_merge);
417
338
}
418
419
MdbBackend *mdbi_register_backend2(MdbHandle *mdb, char *backend_name, guint32 capabilities,
420
        const MdbBackendType *backend_type, const MdbBackendType *type_shortdate, const MdbBackendType *type_autonum,
421
        const char *short_now, const char *long_now,
422
        const char *date_fmt, const char *shortdate_fmt,
423
        const char *charset_statement,
424
        const char *create_table_statement,
425
        const char *drop_statement,
426
        const char *constraint_not_empty_statement,
427
        const char *column_comment_statement,
428
        const char *per_column_comment_statement,
429
        const char *table_comment_statement,
430
        const char *per_table_comment_statement,
431
        gchar* (*quote_schema_name)(const gchar*, const gchar*),
432
2.02k
        gchar* (*normalise_case)(const gchar*)) {
433
2.02k
  MdbBackend *backend = g_malloc0(sizeof(MdbBackend));
434
2.02k
  backend->capabilities = capabilities;
435
2.02k
  backend->types_table = backend_type;
436
2.02k
  backend->type_shortdate = type_shortdate;
437
2.02k
  backend->type_autonum = type_autonum;
438
2.02k
  backend->short_now = short_now;
439
2.02k
  backend->long_now = long_now;
440
2.02k
  backend->date_fmt = date_fmt;
441
2.02k
  backend->shortdate_fmt = shortdate_fmt;
442
2.02k
  backend->charset_statement = charset_statement;
443
2.02k
  backend->create_table_statement = create_table_statement;
444
2.02k
  backend->drop_statement = drop_statement;
445
2.02k
  backend->constaint_not_empty_statement = constraint_not_empty_statement;
446
2.02k
  backend->column_comment_statement = column_comment_statement;
447
2.02k
  backend->per_column_comment_statement = per_column_comment_statement;
448
2.02k
  backend->table_comment_statement = table_comment_statement;
449
2.02k
  backend->per_table_comment_statement = per_table_comment_statement;
450
2.02k
  backend->quote_schema_name  = quote_schema_name;
451
2.02k
  backend->normalise_case = normalise_case;
452
2.02k
  g_hash_table_insert(mdb->backends, backend_name, backend);
453
2.02k
    return backend;
454
2.02k
}
455
456
void mdb_register_backend(MdbHandle *mdb, char *backend_name, guint32 capabilities,
457
        const MdbBackendType *backend_type, const MdbBackendType *type_shortdate, const MdbBackendType *type_autonum,
458
        const char *short_now, const char *long_now,
459
        const char *date_fmt, const char *shortdate_fmt,
460
        const char *charset_statement,
461
        const char *drop_statement,
462
        const char *constraint_not_empty_statement,
463
        const char *column_comment_statement,
464
        const char *per_column_comment_statement,
465
        const char *table_comment_statement,
466
        const char *per_table_comment_statement,
467
        gchar* (*quote_schema_name)(const gchar*, const gchar*))
468
1.69k
{
469
1.69k
    mdbi_register_backend2(mdb, backend_name, capabilities,
470
1.69k
            backend_type, type_shortdate, type_autonum,
471
1.69k
            short_now, long_now,
472
1.69k
            date_fmt, shortdate_fmt,
473
1.69k
            charset_statement,
474
1.69k
            "CREATE TABLE %s\n",
475
1.69k
            drop_statement,
476
1.69k
            constraint_not_empty_statement,
477
1.69k
            column_comment_statement,
478
1.69k
            per_column_comment_statement,
479
1.69k
            table_comment_statement,
480
1.69k
            per_table_comment_statement,
481
1.69k
            quote_schema_name,
482
1.69k
            passthrough_unchanged);
483
1.69k
}
484
485
/**
486
 * mdb_remove_backends
487
 *
488
 * Removes all entries from and destroys the mdb_backends hash.
489
 */
490
void
491
mdb_remove_backends(MdbHandle *mdb)
492
338
{
493
338
  g_hash_table_foreach(mdb->backends, mdb_drop_backend, NULL);
494
338
  g_hash_table_destroy(mdb->backends);
495
338
}
496
static void mdb_drop_backend(gpointer key, gpointer value, gpointer data)
497
2.02k
{
498
2.02k
  MdbBackend *backend = (MdbBackend *)value;
499
2.02k
  g_free (backend);
500
2.02k
}
501
502
/**
503
 * mdb_set_default_backend
504
 * @mdb: Handle to open MDB database file
505
 * @backend_name: Name of the backend to set as default
506
 *
507
 * Sets the default backend of the handle @mdb to @backend_name.
508
 *
509
 * Returns: 1 if successful, 0 if unsuccessful.
510
 */
511
int mdb_set_default_backend(MdbHandle *mdb, const char *backend_name)
512
338
{
513
338
  MdbBackend *backend;
514
515
338
    if (!mdb->backends) {
516
338
        mdb_init_backends(mdb);
517
338
    }
518
338
  backend = (MdbBackend *) g_hash_table_lookup(mdb->backends, backend_name);
519
338
  if (backend) {
520
338
    mdb->default_backend = backend;
521
338
    g_free(mdb->backend_name); // NULL is ok
522
338
    mdb->backend_name = (char *) g_strdup(backend_name);
523
338
    mdb->relationships_table = NULL;
524
338
    if (backend->date_fmt) {
525
0
      mdb_set_date_fmt(mdb, backend->date_fmt);
526
338
    } else {
527
338
      mdb_set_date_fmt(mdb, "%x %X");
528
338
    }
529
338
    if (backend->shortdate_fmt) {
530
0
      mdb_set_shortdate_fmt(mdb, backend->shortdate_fmt);
531
338
    } else {
532
338
      mdb_set_shortdate_fmt(mdb, "%x");
533
338
    }
534
338
  }
535
338
  return (backend != NULL);
536
338
}
537
538
539
/**
540
 * Generates index name based on backend.
541
 *
542
 * You should free() the returned value once you are done with it.
543
 *
544
 * @param backend backend we are generating indexes for
545
 * @param table table being processed
546
 * @param idx index being processed
547
 * @return the index name
548
 */
549
static char *
550
mdb_get_index_name(int backend, MdbTableDef *table, MdbIndex *idx)
551
0
{
552
0
  char *index_name;
553
554
0
  switch(backend){
555
0
    case MDB_BACKEND_MYSQL:
556
      // appending table name to index often makes it too long for mysql
557
0
      if (idx->index_type==1)
558
        // for mysql name of primary key is not used
559
0
        index_name = g_strdup("_pkey");
560
0
      else {
561
0
        index_name = g_strdup(idx->name);
562
0
      }
563
0
      break;
564
0
    default:
565
0
      if (idx->index_type==1)
566
0
        index_name = g_strconcat(table->name, "_pkey", NULL);
567
0
      else {
568
0
        index_name = g_strconcat(table->name, "_", idx->name, "_idx", NULL);
569
0
      }
570
0
  }
571
572
0
  return index_name;
573
0
}
574
/**
575
 * mdb_print_pk - print primary key constraint
576
 * @output: Where to print the sql
577
 * @table: Table to process
578
 */
579
static void
580
mdb_print_pk_if_sqlite(FILE *outfile, MdbTableDef *table)
581
0
{
582
0
  unsigned int i, j;
583
0
  MdbHandle *mdb = table->entry->mdb;
584
0
  MdbIndex *idx;
585
0
  MdbColumn *col;
586
0
  char *quoted_name;
587
  // this is only necessary for sqlite
588
0
  if (strcmp(mdb->backend_name, "sqlite") != 0)
589
0
    return;
590
591
0
  if (table->indices==NULL)
592
0
    mdb_read_indices(table);
593
    
594
0
  for (i = 0; i < table->num_idxs; i++) {
595
0
    idx = g_ptr_array_index(table->indices, i);
596
0
    if (idx->index_type == 1) {
597
0
      fprintf(outfile, "\t, PRIMARY KEY (");
598
0
      for (j = 0; j < idx->num_keys; j++) {
599
0
        if (j)
600
0
          fprintf(outfile, ", ");
601
0
        col = g_ptr_array_index(table->columns, idx->key_col_num[j] - 1);
602
0
        quoted_name = mdb->default_backend->quote_schema_name(NULL, col->name);
603
0
        quoted_name = mdb_normalise_and_replace(mdb, &quoted_name);
604
0
        fprintf(outfile, "%s", quoted_name);
605
0
        if (idx->index_type != 1 && idx->key_col_order[j])
606
          /* no DESC for primary keys */
607
0
          fprintf(outfile, " DESC");
608
609
0
        g_free(quoted_name);
610
0
      }
611
0
      fprintf(outfile, ")\n");
612
0
    }
613
0
  }
614
0
}
615
/**
616
 * mdb_print_indexes
617
 * @output: Where to print the sql
618
 * @table: Table to process
619
 * @dbnamespace: Target namespace/schema name
620
 */
621
static void
622
mdb_print_indexes(FILE* outfile, MdbTableDef *table, char *dbnamespace)
623
0
{
624
0
  unsigned int i, j;
625
0
  char* quoted_table_name;
626
0
  char* index_name;
627
0
  char* quoted_name;
628
0
  int backend;
629
0
  MdbHandle* mdb = table->entry->mdb;
630
0
  MdbIndex *idx;
631
0
  MdbColumn *col;
632
633
0
  if (!strcmp(mdb->backend_name, "postgres")) {
634
0
    backend = MDB_BACKEND_POSTGRES;
635
0
  } else if (!strcmp(mdb->backend_name, "mysql")) {
636
0
    backend = MDB_BACKEND_MYSQL;
637
0
  } else if (!strcmp(mdb->backend_name, "oracle")) {
638
0
    backend = MDB_BACKEND_ORACLE;
639
0
  } else if (!strcmp(mdb->backend_name, "sqlite")) {
640
0
    backend = MDB_BACKEND_SQLITE;
641
0
  } else {
642
0
    fprintf(outfile, "-- Indexes are not implemented for %s\n\n", mdb->backend_name);
643
0
    return;
644
0
  }
645
646
  /* read indexes */
647
0
  if (table->indices==NULL)
648
0
    mdb_read_indices(table);
649
650
0
  fprintf (outfile, "-- CREATE INDEXES ...\n");
651
652
0
  quoted_table_name = mdb->default_backend->quote_schema_name(dbnamespace, table->name);
653
0
  quoted_table_name = mdb->default_backend->normalise_case(quoted_table_name);
654
655
0
  for (i=0;i<table->num_idxs;i++) {
656
0
    idx = g_ptr_array_index (table->indices, i);
657
0
    if (idx->index_type==2)
658
0
      continue;
659
    /* Sqlite3 primary keys have to be issued as a table constraint */
660
0
    if (idx->index_type == 1 && backend == MDB_BACKEND_SQLITE)
661
0
      continue;
662
663
0
    index_name = mdb_get_index_name(backend, table, idx);
664
0
    switch (backend) {
665
0
      case MDB_BACKEND_POSTGRES:
666
        /* PostgreSQL index and constraint names are
667
                                 * never namespaced in DDL (they are always
668
                                 * created in same namespace as table), so
669
                                 * omit namespace.
670
                                 */
671
0
        quoted_name = mdb->default_backend->quote_schema_name(NULL, index_name);
672
0
        break;
673
674
0
                         default:
675
0
        quoted_name = mdb->default_backend->quote_schema_name(dbnamespace, index_name);
676
0
    }
677
678
0
    quoted_name = mdb_normalise_and_replace(mdb, &quoted_name);
679
0
    if (idx->num_keys == 0) {
680
0
      fprintf(outfile, "-- WARNING: found no keys for index %s - ignored\n", quoted_name);
681
0
      continue;
682
0
    }
683
0
    if (idx->index_type==1) {
684
0
      switch (backend) {
685
0
        case MDB_BACKEND_ORACLE:
686
0
        case MDB_BACKEND_POSTGRES:
687
0
          fprintf (outfile, "ALTER TABLE %s ADD CONSTRAINT %s PRIMARY KEY (", quoted_table_name, quoted_name);
688
0
          break;
689
0
        case MDB_BACKEND_MYSQL:
690
0
          fprintf (outfile, "ALTER TABLE %s ADD PRIMARY KEY (", quoted_table_name);
691
0
          break;
692
0
      }
693
0
    } else {
694
0
      switch (backend) {
695
0
        case MDB_BACKEND_ORACLE:
696
0
        case MDB_BACKEND_POSTGRES:
697
0
        case MDB_BACKEND_SQLITE:
698
0
          fprintf(outfile, "CREATE");
699
0
          if (idx->flags & MDB_IDX_UNIQUE)
700
0
            fprintf (outfile, " UNIQUE");
701
0
          fprintf(outfile, " INDEX %s ON %s (", quoted_name, quoted_table_name);
702
0
          break;
703
0
        case MDB_BACKEND_MYSQL:
704
0
          fprintf(outfile, "ALTER TABLE %s ADD", quoted_table_name);
705
0
          if (idx->flags & MDB_IDX_UNIQUE)
706
0
            fprintf (outfile, " UNIQUE");
707
0
          fprintf(outfile, " INDEX %s (", quoted_name);
708
0
          break;
709
0
      }
710
0
    }
711
0
    g_free(quoted_name);
712
0
    free(index_name);
713
714
0
    for (j=0;j<idx->num_keys;j++) {
715
0
      if (j)
716
0
        fprintf(outfile, ", ");
717
0
      col=g_ptr_array_index(table->columns,idx->key_col_num[j]-1);
718
0
      quoted_name = mdb->default_backend->quote_schema_name(NULL, col->name);
719
0
      quoted_name = mdb_normalise_and_replace(mdb, &quoted_name);
720
0
      fprintf (outfile, "%s", quoted_name);
721
0
      if (idx->index_type!=1 && idx->key_col_order[j])
722
        /* no DESC for primary keys */
723
0
        fprintf(outfile, " DESC");
724
725
0
      g_free(quoted_name);
726
727
0
    }
728
0
    fprintf (outfile, ");\n");
729
0
  }
730
0
  fputc ('\n', outfile);
731
732
0
  g_free(quoted_table_name);
733
0
}
734
735
/**
736
 * mdb_get_relationships
737
 * @mdb: Handle to open MDB database file
738
 * @tablename: Name of the table to process. Process all tables if NULL.
739
 *
740
 * Generates relationships by reading the MSysRelationships table.
741
 *   'szColumn' contains the column name of the child table.
742
 *   'szObject' contains the table name of the child table.
743
 *   'szReferencedColumn' contains the column name of the parent table.
744
 *   'szReferencedObject' contains the table name of the parent table.
745
 *   'grbit' contains integrity constraints.
746
 *
747
 * Returns: a string stating that relationships are not supported for the
748
 *   selected backend, or a string containing SQL commands for setting up
749
 *   the relationship, tailored for the selected backend.
750
 *   Returns NULL on last iteration.
751
 *   The caller is responsible for freeing this string.
752
 */
753
static char *
754
mdb_get_relationships(MdbHandle *mdb, const gchar *dbnamespace, const char* tablename)
755
0
{
756
0
  unsigned int i;
757
0
  gchar *text = NULL;  /* String to be returned */
758
0
  char **bound = mdb->relationships_values;  /* Bound values */
759
0
  int backend = 0;
760
0
  char *quoted_table_1, *quoted_column_1,
761
0
       *quoted_table_2, *quoted_column_2,
762
0
       *constraint_name, *quoted_constraint_name;
763
0
  long grbit;
764
765
0
  if (!strcmp(mdb->backend_name, "oracle")) {
766
0
    backend = MDB_BACKEND_ORACLE;
767
0
  } else if (!strcmp(mdb->backend_name, "postgres")) {
768
0
    backend = MDB_BACKEND_POSTGRES;
769
0
  } else if (!strcmp(mdb->backend_name, "mysql")) {
770
0
    backend = MDB_BACKEND_MYSQL;
771
0
  } else if (!mdb->relationships_table) {
772
0
    return NULL;
773
0
  }
774
775
0
  if (!mdb->relationships_table) {
776
0
    mdb->relationships_table = mdb_read_table_by_name(mdb, "MSysRelationships", MDB_TABLE);
777
0
    if (!mdb->relationships_table || !mdb->relationships_table->num_rows) {
778
0
      fprintf(stderr, "No MSysRelationships\n");
779
0
      return NULL;
780
0
    }
781
0
    if (!mdb_read_columns(mdb->relationships_table)) {
782
0
      fprintf(stderr, "Unable to read columns of MSysRelationships\n");
783
0
      return NULL;
784
0
    }
785
0
    for (i=0;i<5;i++) {
786
0
      bound[i] = g_malloc0(mdb->bind_size);
787
0
    }
788
0
    mdb_bind_column_by_name(mdb->relationships_table, "szColumn", bound[0], NULL);
789
0
    mdb_bind_column_by_name(mdb->relationships_table, "szObject", bound[1], NULL);
790
0
    mdb_bind_column_by_name(mdb->relationships_table, "szReferencedColumn", bound[2], NULL);
791
0
    mdb_bind_column_by_name(mdb->relationships_table, "szReferencedObject", bound[3], NULL);
792
0
    mdb_bind_column_by_name(mdb->relationships_table, "grbit", bound[4], NULL);
793
0
    mdb_rewind_table(mdb->relationships_table);
794
0
  }
795
0
    if (mdb->relationships_table->cur_row >= mdb->relationships_table->num_rows) {  /* past the last row */
796
0
        for (i=0;i<5;i++)
797
0
            g_free(bound[i]);
798
0
        mdb->relationships_table = NULL;
799
0
        return NULL;
800
0
    }
801
802
0
  while (1) {
803
0
    if (!mdb_fetch_row(mdb->relationships_table)) {
804
0
      for (i=0;i<5;i++)
805
0
        g_free(bound[i]);
806
0
      mdb->relationships_table = NULL;
807
0
      return NULL;
808
0
    }
809
0
    if (!tablename || !strcmp(bound[1], tablename))
810
0
      break;
811
0
  }
812
813
0
  quoted_table_1 = mdb->default_backend->quote_schema_name(dbnamespace, bound[1]);
814
0
  quoted_table_2 = mdb->default_backend->quote_schema_name(dbnamespace, bound[3]);
815
0
  grbit = atoi(bound[4]);
816
0
  constraint_name = g_strconcat(bound[1], "_", bound[0], "_fk", NULL);
817
818
0
  switch (backend) {
819
0
    case MDB_BACKEND_POSTGRES:
820
      /* PostgreSQL index and constraint names are
821
       * never namespaced in DDL (they are always
822
       * created in same namespace as table), so
823
       * omit namespace.  Nor should column names
824
                         * be namespaced.
825
       */
826
0
      quoted_constraint_name = mdb->default_backend->quote_schema_name(NULL, constraint_name);
827
0
      quoted_constraint_name = mdb_normalise_and_replace(mdb, &quoted_constraint_name);
828
0
      quoted_column_1 = mdb->default_backend->quote_schema_name(NULL, bound[0]);
829
0
      quoted_column_1 = mdb_normalise_and_replace(mdb, &quoted_column_1);
830
0
      quoted_column_2 = mdb->default_backend->quote_schema_name(NULL, bound[2]);
831
0
      quoted_column_2 = mdb_normalise_and_replace(mdb, &quoted_column_2);
832
0
      break;
833
834
0
    default:
835
      /* Other databases, namespace constraint and
836
       * column names.
837
       */
838
0
      quoted_constraint_name = mdb->default_backend->quote_schema_name(dbnamespace, constraint_name);
839
0
      quoted_column_1 = mdb->default_backend->quote_schema_name(dbnamespace, bound[0]);
840
0
      quoted_column_2 = mdb->default_backend->quote_schema_name(dbnamespace, bound[2]);
841
0
      break;
842
0
  }
843
0
  g_free(constraint_name);
844
845
0
  if (grbit & 0x00000002) {
846
0
    text = g_strconcat(
847
0
      "-- Relationship from ", quoted_table_1,
848
0
      " (", quoted_column_1, ")"
849
0
      " to ", quoted_table_2, "(", quoted_column_2, ")",
850
0
      " does not enforce integrity.\n", NULL);
851
0
  } else {
852
0
    switch (backend) {
853
0
      case MDB_BACKEND_ORACLE:
854
0
                        text = g_strconcat(
855
0
                                "ALTER TABLE ", quoted_table_1,
856
0
                                " ADD CONSTRAINT ", quoted_constraint_name,
857
0
                                " FOREIGN KEY (", quoted_column_1, ")"
858
0
                                " REFERENCES ", quoted_table_2, "(", quoted_column_2, ")",
859
0
                                (grbit & 0x00001000) ? " ON DELETE CASCADE" : "",
860
0
                                ";\n", NULL);
861
862
0
                        break;
863
0
      case MDB_BACKEND_MYSQL:
864
0
      text = g_strconcat(
865
0
        "ALTER TABLE ", quoted_table_1,
866
0
        " ADD CONSTRAINT ", quoted_constraint_name,
867
0
        " FOREIGN KEY (", quoted_column_1, ")"
868
0
        " REFERENCES ", quoted_table_2, "(", quoted_column_2, ")",
869
0
        (grbit & 0x00000100) ? " ON UPDATE CASCADE" : "",
870
0
        (grbit & 0x00001000) ? " ON DELETE CASCADE" : "",
871
0
        ";\n", NULL);
872
0
      break;
873
0
      case MDB_BACKEND_POSTGRES:
874
0
      text = g_strconcat(
875
0
        "ALTER TABLE ", quoted_table_1,
876
0
        " ADD CONSTRAINT ", quoted_constraint_name,
877
0
        " FOREIGN KEY (", quoted_column_1, ")"
878
0
        " REFERENCES ", quoted_table_2, "(", quoted_column_2, ")",
879
0
        (grbit & 0x00000100) ? " ON UPDATE CASCADE" : "",
880
0
        (grbit & 0x00001000) ? " ON DELETE CASCADE" : "",
881
        /* On some databases (eg PostgreSQL) we also want to set
882
         * the constraints to be optionally deferrable, to
883
         * facilitate out of order bulk loading.
884
         */
885
0
        " DEFERRABLE",
886
0
        " INITIALLY IMMEDIATE",
887
0
        ";\n", NULL);
888
889
0
      break;
890
0
    }
891
0
  }
892
0
  g_free(quoted_table_1);
893
0
  g_free(quoted_column_1);
894
0
  g_free(quoted_table_2);
895
0
  g_free(quoted_column_2);
896
0
  g_free(quoted_constraint_name);
897
898
0
  return (char *)text;
899
0
}
900
901
static void
902
generate_table_schema(FILE *outfile, MdbCatalogEntry *entry, char *dbnamespace, guint32 export_options)
903
0
{
904
0
  MdbTableDef *table;
905
0
  MdbHandle *mdb = entry->mdb;
906
0
  MdbColumn *col;
907
0
  unsigned int i;
908
0
  char* quoted_table_name;
909
0
  char* quoted_name;
910
0
  MdbProperties *props;
911
0
  const char *prop_value;
912
913
0
  quoted_table_name = mdb->default_backend->quote_schema_name(dbnamespace, entry->object_name);
914
0
  quoted_table_name = mdb_normalise_and_replace(mdb, &quoted_table_name);
915
916
  /* drop the table if it exists */
917
0
  if (export_options & MDB_SHEXP_DROPTABLE)
918
0
    fprintf (outfile, mdb->default_backend->drop_statement, quoted_table_name);
919
920
  /* create the table */
921
0
  fprintf (outfile, mdb->default_backend->create_table_statement, quoted_table_name);
922
0
  fprintf (outfile, " (\n");
923
924
0
  table = mdb_read_table (entry);
925
0
  if (!table) {
926
0
    fprintf(stderr, "Error: Table %s does not exist\n", entry->object_name);
927
0
    return;
928
0
  }
929
930
  /* get the columns */
931
0
  mdb_read_columns(table);
932
933
  /* loop over the columns, dumping the names and types */
934
0
  for (i = 0; i < table->num_cols; i++) {
935
0
    col = g_ptr_array_index (table->columns, i);
936
937
0
    quoted_name = mdb->default_backend->quote_schema_name(NULL, col->name);
938
0
    quoted_name = mdb_normalise_and_replace(mdb, &quoted_name);
939
0
    fprintf (outfile, "\t%s\t\t\t%s", quoted_name,
940
0
      mdb_get_colbacktype_string (col));
941
0
    g_free(quoted_name);
942
943
0
    if (mdb_colbacktype_takes_length(col)) {
944
      /* more portable version from DW patch */
945
0
      if (col->col_size == 0)
946
0
        fputs(" (255)", outfile);
947
0
      else if (col->col_scale != 0)
948
0
        fprintf(outfile, " (%d, %d)", col->col_scale, col->col_prec);
949
0
      else if (!IS_JET3(mdb) && mdb_colbacktype_takes_length_in_characters(col))
950
0
        fprintf(outfile, " (%d)", col->col_size/2);
951
0
      else
952
0
        fprintf(outfile, " (%d)", col->col_size);
953
0
    }
954
955
0
    if (mdb->default_backend->per_column_comment_statement && export_options & MDB_SHEXP_COMMENTS) {
956
0
      prop_value = mdb_col_get_prop(col, "Description");
957
0
      if (prop_value) {
958
0
        char *comment = quote_with_squotes(prop_value);
959
0
        fputs(" ", outfile);
960
0
        fprintf(outfile,
961
0
          mdb->default_backend->per_column_comment_statement,
962
0
          comment);
963
0
        free(comment);
964
0
      }
965
0
    }
966
967
0
    if (export_options & MDB_SHEXP_CST_NOTNULL) {
968
0
      if (col->col_type == MDB_BOOL) {
969
        /* access booleans are never null */
970
0
        fputs(" NOT NULL", outfile);
971
0
      } else {
972
0
        const gchar *not_null = mdb_col_get_prop(col, "Required");
973
0
        if (not_null && not_null[0]=='y')
974
0
          fputs(" NOT NULL", outfile);
975
0
      }
976
0
    }
977
978
0
    if (export_options & MDB_SHEXP_DEFVALUES) {
979
0
      int done = 0;
980
0
      if (col->props) {
981
0
        gchar *defval = g_hash_table_lookup(col->props->hash, "DefaultValue");
982
0
        if (defval) {
983
0
          size_t def_len = strlen(defval);
984
0
          fputs(" DEFAULT ", outfile);
985
          /* ugly hack to detect the type */
986
0
          if (defval[0]=='"' && defval[def_len-1]=='"') {
987
            /* this is a string */
988
0
            gchar *output_default = malloc(def_len-1);
989
0
            gchar *output_default_escaped;
990
0
            memcpy(output_default, defval+1, def_len-2);
991
0
            output_default[def_len-2] = 0;
992
0
            output_default_escaped = quote_with_squotes(output_default);
993
0
            fputs(output_default_escaped, outfile);
994
0
            g_free(output_default_escaped);
995
0
            free(output_default);
996
0
          } else if (!strcmp(defval, "Yes"))
997
0
            fputs("TRUE", outfile);
998
0
          else if (!strcmp(defval, "No"))
999
0
            fputs("FALSE", outfile);
1000
0
          else if (!g_ascii_strcasecmp(defval, "date()")) {
1001
0
            if (mdb_col_is_shortdate(col))
1002
0
              fputs(mdb->default_backend->short_now, outfile);
1003
0
            else
1004
0
              fputs(mdb->default_backend->long_now, outfile);
1005
0
          }
1006
0
          else
1007
0
            fputs(defval, outfile);
1008
0
          done = 1;
1009
0
        }
1010
0
      }
1011
0
      if (!done && col->col_type == MDB_BOOL)
1012
        /* access booleans are false by default */
1013
0
        fputs(" DEFAULT FALSE", outfile);
1014
0
    }
1015
0
    if (i < table->num_cols - 1)
1016
0
      fputs(", \n", outfile);
1017
0
    else
1018
0
      fputs("\n", outfile);
1019
0
  } /* for */
1020
1021
0
  if (export_options & MDB_SHEXP_INDEXES) {
1022
    // sqlite does not support ALTER TABLE PRIMARY KEY, so we need to place it directly into CREATE TABLE
1023
0
    mdb_print_pk_if_sqlite(outfile, table);
1024
0
  }
1025
1026
0
  fputs(")", outfile);
1027
0
  if (mdb->default_backend->per_table_comment_statement && export_options & MDB_SHEXP_COMMENTS) {
1028
0
    prop_value = mdb_table_get_prop(table, "Description");
1029
0
    if (prop_value) {
1030
0
      char *comment = quote_with_squotes(prop_value);
1031
0
      fputs(" ", outfile);
1032
0
      fprintf(outfile, mdb->default_backend->per_table_comment_statement, comment);
1033
0
      free(comment);
1034
0
    }
1035
0
  }
1036
0
  fputs(";\n", outfile);
1037
1038
  /* Add the constraints on columns */
1039
0
  for (i = 0; i < table->num_cols; i++) {
1040
0
    col = g_ptr_array_index (table->columns, i);
1041
0
    props = col->props;
1042
0
    if (!props)
1043
0
      continue;
1044
1045
0
    quoted_name = mdb->default_backend->quote_schema_name(NULL, col->name);
1046
0
    quoted_name = mdb_normalise_and_replace(mdb, &quoted_name);
1047
1048
0
    if (export_options & MDB_SHEXP_CST_NOTEMPTY) {
1049
0
      prop_value = mdb_col_get_prop(col, "AllowZeroLength");
1050
0
      if (prop_value && prop_value[0]=='n')
1051
0
          fprintf(outfile,
1052
0
            mdb->default_backend->constaint_not_empty_statement,
1053
0
            quoted_table_name, quoted_name);
1054
0
    }
1055
1056
0
    if (mdb->default_backend->column_comment_statement && export_options & MDB_SHEXP_COMMENTS) {
1057
0
      prop_value = mdb_col_get_prop(col, "Description");
1058
0
      if (prop_value) {
1059
0
        char *comment = quote_with_squotes(prop_value);
1060
0
        fprintf(outfile,
1061
0
          mdb->default_backend->column_comment_statement,
1062
0
          quoted_table_name, quoted_name, comment);
1063
0
        g_free(comment);
1064
0
      }
1065
0
    }
1066
1067
0
    g_free(quoted_name);
1068
0
  }
1069
1070
  /* Add the constraints on table */
1071
0
  if (mdb->default_backend->table_comment_statement && export_options & MDB_SHEXP_COMMENTS) {
1072
0
    prop_value = mdb_table_get_prop(table, "Description");
1073
0
    if (prop_value) {
1074
0
      char *comment = quote_with_squotes(prop_value);
1075
0
      fprintf(outfile,
1076
0
        mdb->default_backend->table_comment_statement,
1077
0
        quoted_table_name, comment);
1078
0
      g_free(comment);
1079
0
    }
1080
0
  }
1081
0
  fputc('\n', outfile);
1082
1083
1084
0
  if (export_options & MDB_SHEXP_INDEXES)
1085
    // prints all the indexes of that table
1086
0
    mdb_print_indexes(outfile, table, dbnamespace);
1087
1088
0
  g_free(quoted_table_name);
1089
1090
0
  mdb_free_tabledef (table);
1091
0
}
1092
1093
1094
int
1095
mdb_print_schema(MdbHandle *mdb, FILE *outfile, char *tabname, char *dbnamespace, guint32 export_options)
1096
0
{
1097
0
  unsigned int   i;
1098
0
  char    *the_relation;
1099
0
  MdbCatalogEntry *entry;
1100
0
  const char *charset;
1101
0
  int success = (tabname == NULL);
1102
1103
  /* clear unsupported options */
1104
0
  export_options &= mdb->default_backend->capabilities;
1105
1106
  /* Print out a little message to show that this came from mdb-tools.
1107
     I like to know how something is generated. DW */
1108
0
  fputs("-- ----------------------------------------------------------\n"
1109
0
    "-- MDB Tools - A library for reading MS Access database files\n"
1110
0
    "-- Copyright (C) 2000-2011 Brian Bruns and others.\n"
1111
0
    "-- Files in libmdb are licensed under LGPL and the utilities under\n"
1112
0
    "-- the GPL, see COPYING.LIB and COPYING files respectively.\n"
1113
0
    "-- Check out http://mdbtools.sourceforge.net\n"
1114
0
    "-- ----------------------------------------------------------\n\n",
1115
0
    outfile);
1116
1117
0
  charset = mdb_target_charset(mdb);
1118
0
  if (charset) {
1119
0
    fprintf(outfile, mdb->default_backend->charset_statement, charset);
1120
0
    fputc('\n', outfile);
1121
0
  }
1122
1123
0
  for (i=0; i < mdb->num_catalog; i++) {
1124
0
    entry = g_ptr_array_index (mdb->catalog, i);
1125
0
    if (entry->object_type == MDB_TABLE) {
1126
0
      if ((tabname && !strcmp(entry->object_name, tabname))
1127
0
       || (!tabname && mdb_is_user_table(entry))) {
1128
0
        generate_table_schema(outfile, entry, dbnamespace, export_options);
1129
0
        success = 1;
1130
0
      }
1131
0
    }
1132
0
  }
1133
0
  fprintf (outfile, "\n");
1134
1135
0
  if (export_options & MDB_SHEXP_RELATIONS) {
1136
0
    fputs ("-- CREATE Relationships ...\n", outfile);
1137
0
    the_relation=mdb_get_relationships(mdb, dbnamespace, tabname);
1138
0
    if (!the_relation) {
1139
0
      fputs("-- relationships are not implemented for ", outfile);
1140
0
      fputs(mdb->backend_name, outfile);
1141
0
      fputs("\n", outfile);
1142
0
    } else {
1143
0
      do {
1144
0
        fputs(the_relation, outfile);
1145
0
        g_free(the_relation);
1146
0
      } while ((the_relation=mdb_get_relationships(mdb, dbnamespace, tabname)) != NULL);
1147
0
    }
1148
0
  }
1149
0
  return success;
1150
0
}
1151
1152
0
#define MDB_BINEXPORT_MASK 0x0F
1153
0
#define is_binary_type(x) (x==MDB_OLE || x==MDB_BINARY || x==MDB_REPID)
1154
0
#define is_quote_type(x) (is_binary_type(x) || x==MDB_TEXT || x==MDB_MEMO || x==MDB_DATETIME)
1155
//#define DONT_ESCAPE_ESCAPE
1156
void
1157
mdb_print_col(FILE *outfile, gchar *col_val, int quote_text, int col_type, int bin_len,
1158
    char *quote_char, char *escape_char, int flags)
1159
/* quote_text: Don't quote if 0.
1160
 */
1161
0
{
1162
0
  size_t quote_len = strlen(quote_char); /* multibyte */
1163
1164
0
  size_t orig_escape_len = escape_char ? strlen(escape_char) : 0;
1165
0
  int quoting = quote_text && is_quote_type(col_type);
1166
0
    int bin_mode = (flags & MDB_BINEXPORT_MASK);
1167
0
    int escape_cr_lf = !!(flags & MDB_EXPORT_ESCAPE_CONTROL_CHARS);
1168
1169
  /* double the quote char if no escape char passed */
1170
0
  if (!escape_char)
1171
0
    escape_char = quote_char;
1172
1173
0
  if (quoting)
1174
0
    fputs(quote_char, outfile);
1175
1176
0
  while (1) {
1177
0
    if (is_binary_type(col_type)) {
1178
0
      if (bin_mode == MDB_BINEXPORT_STRIP)
1179
0
        break;
1180
0
      if (!bin_len--)
1181
0
        break;
1182
0
    } else /* use \0 sentry */
1183
0
      if (!*col_val)
1184
0
        break;
1185
1186
0
    if (is_binary_type(col_type) && bin_mode == MDB_BINEXPORT_OCTAL) {
1187
0
      fprintf(outfile, "\\%03o", *(unsigned char*)col_val++);
1188
0
    } else if (is_binary_type(col_type) && bin_mode == MDB_BINEXPORT_HEXADECIMAL) {
1189
0
      fprintf(outfile, "%02X", *(unsigned char*)col_val++);
1190
0
    } else if (quoting && quote_len && !strncmp(col_val, quote_char, quote_len)) {
1191
0
      fprintf(outfile, "%s%s", escape_char, quote_char);
1192
0
      col_val += quote_len;
1193
0
#ifndef DONT_ESCAPE_ESCAPE
1194
0
    } else if (quoting && orig_escape_len && !strncmp(col_val, escape_char, orig_escape_len)) {
1195
0
      fprintf(outfile, "%s%s", escape_char, escape_char);
1196
0
      col_val += orig_escape_len;
1197
0
#endif
1198
0
    } else if (escape_cr_lf && is_quote_type(col_type) && *col_val=='\r') {
1199
0
      col_val++;
1200
0
      putc('\\', outfile);
1201
0
      putc('r', outfile);
1202
0
    } else if (escape_cr_lf && is_quote_type(col_type) && *col_val=='\n') {
1203
0
      col_val++;
1204
0
      putc('\\', outfile);
1205
0
      putc('n', outfile);
1206
0
    } else if (escape_cr_lf && is_quote_type(col_type) && *col_val=='\t') {
1207
0
      col_val++;
1208
0
      putc('\\', outfile);
1209
0
      putc('t', outfile);
1210
0
    } else if (escape_cr_lf && is_quote_type(col_type) && *col_val=='\\') {
1211
0
      col_val++;
1212
0
      putc('\\', outfile);
1213
0
      putc('\\', outfile);
1214
0
    } else
1215
0
      putc(*col_val++, outfile);
1216
0
  }
1217
0
  if (quoting)
1218
0
    fputs(quote_char, outfile);
1219
0
}