Revert "winex11.drv: Optimise getting the bits of a DIB after calling SetDIBits."
[wine] / dlls / msi / database.c
1 /*
2  * Implementation of the Microsoft Installer (msi.dll)
3  *
4  * Copyright 2002,2003,2004,2005 Mike McCormack for CodeWeavers
5  *
6  * This library is free software; you can redistribute it and/or
7  * modify it under the terms of the GNU Lesser General Public
8  * License as published by the Free Software Foundation; either
9  * version 2.1 of the License, or (at your option) any later version.
10  *
11  * This library is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
14  * Lesser General Public License for more details.
15  *
16  * You should have received a copy of the GNU Lesser General Public
17  * License along with this library; if not, write to the Free Software
18  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
19  */
20
21 #include <stdarg.h>
22
23 #define COBJMACROS
24 #define NONAMELESSUNION
25
26 #include "windef.h"
27 #include "winbase.h"
28 #include "winreg.h"
29 #include "winnls.h"
30 #include "wine/debug.h"
31 #include "wine/unicode.h"
32 #include "msi.h"
33 #include "msiquery.h"
34 #include "msipriv.h"
35 #include "objidl.h"
36 #include "objbase.h"
37 #include "msiserver.h"
38
39 #include "initguid.h"
40
41 WINE_DEFAULT_DEBUG_CHANNEL(msi);
42
43 DEFINE_GUID( CLSID_MsiDatabase, 0x000c1084, 0x0000, 0x0000,
44              0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46);
45 DEFINE_GUID( CLSID_MsiPatch, 0x000c1086, 0x0000, 0x0000,
46              0xc0,0x00,0x00,0x00,0x00,0x00,0x00,0x46);
47
48 /*
49  *  .MSI  file format
50  *
51  *  An .msi file is a structured storage file.
52  *  It contains a number of streams.
53  *  A stream for each table in the database.
54  *  Two streams for the string table in the database.
55  *  Any binary data in a table is a reference to a stream.
56  */
57
58 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
59 {
60     MSIDATABASE *db = (MSIDATABASE *) arg;
61
62     msi_free(db->path);
63     free_cached_tables( db );
64     msi_free_transforms( db );
65     msi_destroy_stringtable( db->strings );
66     IStorage_Release( db->storage );
67     if (db->deletefile)
68     {
69         DeleteFileW( db->deletefile );
70         msi_free( db->deletefile );
71     }
72 }
73
74 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
75 {
76     IStorage *stg = NULL;
77     HRESULT r;
78     MSIDATABASE *db = NULL;
79     UINT ret = ERROR_FUNCTION_FAILED;
80     LPCWSTR szMode, save_path;
81     STATSTG stat;
82     BOOL created = FALSE;
83     WCHAR path[MAX_PATH];
84
85     static const WCHAR backslash[] = {'\\',0};
86     static const WCHAR szTables[]  = { '_','T','a','b','l','e','s',0 };
87
88     TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
89
90     if( !pdb )
91         return ERROR_INVALID_PARAMETER;
92
93     if (szPersist - MSIDBOPEN_PATCHFILE >= MSIDBOPEN_READONLY &&
94         szPersist - MSIDBOPEN_PATCHFILE <= MSIDBOPEN_CREATEDIRECT)
95     {
96         TRACE("Database is a patch\n");
97         szPersist -= MSIDBOPEN_PATCHFILE;
98     }
99
100     save_path = szDBPath;
101     szMode = szPersist;
102     if( HIWORD( szPersist ) )
103     {
104         if (!CopyFileW( szDBPath, szPersist, FALSE ))
105             return ERROR_OPEN_FAILED;
106
107         szDBPath = szPersist;
108         szPersist = MSIDBOPEN_TRANSACT;
109         created = TRUE;
110     }
111
112     if( szPersist == MSIDBOPEN_READONLY )
113     {
114         r = StgOpenStorage( szDBPath, NULL,
115               STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
116     }
117     else if( szPersist == MSIDBOPEN_CREATE || szPersist == MSIDBOPEN_CREATEDIRECT )
118     {
119         /* FIXME: MSIDBOPEN_CREATE should case STGM_TRANSACTED flag to be
120          * used here: */
121         r = StgCreateDocfile( szDBPath,
122               STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg);
123         if( r == ERROR_SUCCESS )
124         {
125             IStorage_SetClass( stg, &CLSID_MsiDatabase );
126             /* create the _Tables stream */
127             r = write_stream_data(stg, szTables, NULL, 0, TRUE);
128             if (!FAILED(r))
129                 r = msi_init_string_table( stg );
130         }
131         created = TRUE;
132     }
133     else if( szPersist == MSIDBOPEN_TRANSACT )
134     {
135         /* FIXME: MSIDBOPEN_TRANSACT should case STGM_TRANSACTED flag to be
136          * used here: */
137         r = StgOpenStorage( szDBPath, NULL,
138               STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
139     }
140     else if( szPersist == MSIDBOPEN_DIRECT )
141     {
142         r = StgOpenStorage( szDBPath, NULL,
143               STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
144     }
145     else
146     {
147         ERR("unknown flag %p\n",szPersist);
148         return ERROR_INVALID_PARAMETER;
149     }
150
151     if( FAILED( r ) || !stg )
152     {
153         FIXME("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
154         return ERROR_FUNCTION_FAILED;
155     }
156
157     r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
158     if( FAILED( r ) )
159     {
160         FIXME("Failed to stat storage\n");
161         goto end;
162     }
163
164     if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
165          !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) ) 
166     {
167         ERR("storage GUID is not a MSI database GUID %s\n",
168              debugstr_guid(&stat.clsid) );
169         goto end;
170     }
171
172     db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
173                               MSI_CloseDatabase );
174     if( !db )
175     {
176         FIXME("Failed to allocate a handle\n");
177         goto end;
178     }
179
180     if (!strchrW( save_path, '\\' ))
181     {
182         GetCurrentDirectoryW( MAX_PATH, path );
183         lstrcatW( path, backslash );
184         lstrcatW( path, save_path );
185     }
186     else
187         lstrcpyW( path, save_path );
188
189     db->path = strdupW( path );
190
191     if( TRACE_ON( msi ) )
192         enum_stream_names( stg );
193
194     db->storage = stg;
195     db->mode = szMode;
196     if (created)
197         db->deletefile = strdupW( szDBPath );
198     else
199         db->deletefile = NULL;
200     list_init( &db->tables );
201     list_init( &db->transforms );
202
203     db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
204     if( !db->strings )
205         goto end;
206
207     msi_table_set_strref( db->bytes_per_strref );
208     ret = ERROR_SUCCESS;
209
210     msiobj_addref( &db->hdr );
211     IStorage_AddRef( stg );
212     *pdb = db;
213
214 end:
215     if( db )
216         msiobj_release( &db->hdr );
217     if( stg )
218         IStorage_Release( stg );
219
220     return ret;
221 }
222
223 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
224 {
225     MSIDATABASE *db;
226     UINT ret;
227
228     TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
229
230     ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
231     if( ret == ERROR_SUCCESS )
232     {
233         *phDB = alloc_msihandle( &db->hdr );
234         if (! *phDB)
235             ret = ERROR_NOT_ENOUGH_MEMORY;
236         msiobj_release( &db->hdr );
237     }
238
239     return ret;
240 }
241
242 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
243 {
244     HRESULT r = ERROR_FUNCTION_FAILED;
245     LPWSTR szwDBPath = NULL, szwPersist = NULL;
246
247     TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
248
249     if( szDBPath )
250     {
251         szwDBPath = strdupAtoW( szDBPath );
252         if( !szwDBPath )
253             goto end;
254     }
255
256     if( HIWORD(szPersist) )
257     {
258         szwPersist = strdupAtoW( szPersist );
259         if( !szwPersist )
260             goto end;
261     }
262     else
263         szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
264
265     r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
266
267 end:
268     if( HIWORD(szPersist) )
269         msi_free( szwPersist );
270     msi_free( szwDBPath );
271
272     return r;
273 }
274
275 static LPWSTR msi_read_text_archive(LPCWSTR path)
276 {
277     HANDLE file;
278     LPSTR data = NULL;
279     LPWSTR wdata = NULL;
280     DWORD read, size = 0;
281
282     file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
283     if (file == INVALID_HANDLE_VALUE)
284         return NULL;
285
286     size = GetFileSize( file, NULL );
287     data = msi_alloc( size + 1 );
288     if (!data)
289         goto done;
290
291     if (!ReadFile( file, data, size, &read, NULL ))
292         goto done;
293
294     data[size] = '\0';
295     wdata = strdupAtoW( data );
296
297 done:
298     CloseHandle( file );
299     msi_free( data );
300     return wdata;
301 }
302
303 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries)
304 {
305     LPWSTR ptr = *line, save;
306     DWORD i, count = 1;
307
308     *entries = NULL;
309
310     /* stay on this line */
311     while (*ptr && *ptr != '\n')
312     {
313         /* entries are separated by tabs */
314         if (*ptr == '\t')
315             count++;
316
317         ptr++;
318     }
319
320     *entries = msi_alloc(count * sizeof(LPWSTR));
321     if (!*entries)
322         return;
323
324     /* store pointers into the data */
325     for (i = 0, ptr = *line; i < count; i++)
326     {
327         while (*ptr && *ptr == '\r') ptr++;
328         save = ptr;
329
330         while (*ptr && *ptr != '\t' && *ptr != '\n' && *ptr != '\r') ptr++;
331
332         /* NULL-separate the data */
333         if (*ptr == '\n' || *ptr == '\r')
334         {
335             while (*ptr == '\n' || *ptr == '\r')
336                 *(ptr++) = '\0';
337         }
338         else if (*ptr)
339             *ptr++ = '\0';
340
341         (*entries)[i] = save;
342     }
343
344     /* move to the next line if there's more, else EOF */
345     *line = ptr;
346
347     if (num_entries)
348         *num_entries = count;
349 }
350
351 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
352 {
353     LPWSTR prelude;
354     DWORD size;
355
356     static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
357
358     size = sizeof(create_fmt)/sizeof(create_fmt[0]) + lstrlenW(table) - 2;
359     prelude = msi_alloc(size * sizeof(WCHAR));
360     if (!prelude)
361         return NULL;
362
363     sprintfW(prelude, create_fmt, table);
364     return prelude;
365 }
366
367 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
368 {
369     LPWSTR columns, p;
370     LPCWSTR type;
371     DWORD sql_size = 1, i, len;
372     WCHAR expanded[128], *ptr;
373     WCHAR size[10], comma[2], extra[30];
374
375     static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
376     static const WCHAR size_fmt[] = {'(','%','s',')',0};
377     static const WCHAR type_char[] = {'C','H','A','R',0};
378     static const WCHAR type_int[] = {'I','N','T',0};
379     static const WCHAR type_long[] = {'L','O','N','G',0};
380     static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
381     static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
382
383     columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
384     if (!columns)
385         return NULL;
386
387     for (i = 0; i < num_columns; i++)
388     {
389         type = NULL;
390         comma[1] = size[0] = extra[0] = '\0';
391
392         if (i == num_columns - 1)
393             comma[0] = '\0';
394         else
395             comma[0] = ',';
396
397         ptr = &types[i][1];
398         len = atolW(ptr);
399         extra[0] = '\0';
400
401         switch (types[i][0])
402         {
403             case 'l':
404                 lstrcpyW(extra, type_notnull);
405             case 'L':
406                 lstrcatW(extra, localizable);
407                 type = type_char;
408                 sprintfW(size, size_fmt, ptr);
409                 break;
410             case 's':
411                 lstrcpyW(extra, type_notnull);
412             case 'S':
413                 type = type_char;
414                 sprintfW(size, size_fmt, ptr);
415                 break;
416             case 'i':
417                 lstrcpyW(extra, type_notnull);
418             case 'I':
419                 if (len == 2)
420                     type = type_int;
421                 else
422                     type = type_long;
423                 break;
424             default:
425                 ERR("Unknown type: %c\n", types[i][0]);
426                 msi_free(columns);
427                 return NULL;
428         }
429
430         sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
431         sql_size += lstrlenW(expanded);
432
433         p = msi_realloc(columns, sql_size * sizeof(WCHAR));
434         if (!p)
435         {
436             msi_free(columns);
437             return NULL;
438         }
439         columns = p;
440
441         lstrcatW(columns, expanded);
442     }
443
444     return columns;
445 }
446
447 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
448 {
449     LPWSTR postlude, keys, ptr;
450     DWORD size, key_size, i;
451
452     static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
453     static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
454
455     for (i = 0, size = 1; i < num_keys; i++)
456         size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
457
458     keys = msi_alloc(size * sizeof(WCHAR));
459     if (!keys)
460         return NULL;
461
462     for (i = 0, ptr = keys; i < num_keys; i++)
463     {
464         key_size = lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) -2;
465         sprintfW(ptr, key_fmt, primary_keys[i]);
466         ptr += key_size;
467     }
468
469     /* remove final ', ' */
470     *(ptr - 2) = '\0';
471
472     size = lstrlenW(postlude_fmt) + size - 1;
473     postlude = msi_alloc(size * sizeof(WCHAR));
474     if (!postlude)
475         goto done;
476
477     sprintfW(postlude, postlude_fmt, keys);
478
479 done:
480     msi_free(keys);
481     return postlude;
482 }
483
484 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
485 {
486     UINT r;
487     DWORD size;
488     MSIQUERY *view;
489     LPWSTR create_sql;
490     LPWSTR prelude, columns_sql, postlude;
491
492     prelude = msi_build_createsql_prelude(labels[0]);
493     columns_sql = msi_build_createsql_columns(columns, types, num_columns);
494     postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
495
496     if (!prelude || !columns_sql || !postlude)
497         return ERROR_OUTOFMEMORY;
498
499     size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
500     create_sql = msi_alloc(size * sizeof(WCHAR));
501     if (!create_sql)
502         return ERROR_OUTOFMEMORY;
503
504     lstrcpyW(create_sql, prelude);
505     lstrcatW(create_sql, columns_sql);
506     lstrcatW(create_sql, postlude);
507
508     msi_free(prelude);
509     msi_free(columns_sql);
510     msi_free(postlude);
511
512     r = MSI_DatabaseOpenViewW( db, create_sql, &view );
513     msi_free(create_sql);
514
515     if (r != ERROR_SUCCESS)
516         return r;
517
518     r = MSI_ViewExecute(view, NULL);
519     MSI_ViewClose(view);
520     msiobj_release(&view->hdr);
521
522     return r;
523 }
524
525 static UINT construct_record(DWORD num_columns, LPWSTR *types,
526                              LPWSTR *data, MSIRECORD **rec)
527 {
528     UINT i;
529
530     *rec = MSI_CreateRecord(num_columns);
531     if (!*rec)
532         return ERROR_OUTOFMEMORY;
533
534     for (i = 0; i < num_columns; i++)
535     {
536         switch (types[i][0])
537         {
538             case 'L': case 'l': case 'S': case 's':
539                 MSI_RecordSetStringW(*rec, i + 1, data[i]);
540                 break;
541             case 'I': case 'i':
542                 if (*data[i])
543                     MSI_RecordSetInteger(*rec, i + 1, atoiW(data[i]));
544                 break;
545             default:
546                 ERR("Unhandled column type: %c\n", types[i][0]);
547                 msiobj_release(&(*rec)->hdr);
548                 return ERROR_FUNCTION_FAILED;
549         }
550     }
551
552     return ERROR_SUCCESS;
553 }
554
555 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
556                                      LPWSTR *labels, LPWSTR **records,
557                                      int num_columns, int num_records)
558 {
559     UINT r;
560     DWORD i, size;
561     MSIQUERY *view;
562     MSIRECORD *rec;
563     LPWSTR query;
564
565     static const WCHAR select[] = {
566         'S','E','L','E','C','T',' ','*',' ',
567         'F','R','O','M',' ','`','%','s','`',0
568     };
569
570     size = lstrlenW(select) + lstrlenW(labels[0]) - 1;
571     query = msi_alloc(size * sizeof(WCHAR));
572     if (!query)
573         return ERROR_OUTOFMEMORY;
574
575     sprintfW(query, select, labels[0]);
576
577     r = MSI_DatabaseOpenViewW(db, query, &view);
578     msi_free(query);
579     if (r != ERROR_SUCCESS)
580         return r;
581
582     while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
583     {
584         r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
585         if (r != ERROR_SUCCESS)
586             goto done;
587     }
588
589     for (i = 0; i < num_records; i++)
590     {
591         r = construct_record(num_columns, types, records[i], &rec);
592         if (r != ERROR_SUCCESS)
593             goto done;
594
595         r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
596         if (r != ERROR_SUCCESS)
597         {
598             msiobj_release(&rec->hdr);
599             goto done;
600         }
601
602         msiobj_release(&rec->hdr);
603     }
604
605 done:
606     msiobj_release(&view->hdr);
607     return r;
608 }
609
610 UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
611 {
612     UINT r;
613     DWORD len, i;
614     DWORD num_labels, num_types;
615     DWORD num_columns, num_records = 0;
616     LPWSTR *columns, *types, *labels;
617     LPWSTR path, ptr, data;
618     LPWSTR **records = NULL;
619     LPWSTR **temp_records;
620
621     static const WCHAR backslash[] = {'\\',0};
622
623     TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
624
625     if( folder == NULL || file == NULL )
626         return ERROR_INVALID_PARAMETER;
627
628     len = lstrlenW(folder) + lstrlenW(backslash) + lstrlenW(file) + 1;
629     path = msi_alloc( len * sizeof(WCHAR) );
630     if (!path)
631         return ERROR_OUTOFMEMORY;
632
633     lstrcpyW( path, folder );
634     lstrcatW( path, backslash );
635     lstrcatW( path, file );
636
637     data = msi_read_text_archive( path );
638
639     ptr = data;
640     msi_parse_line( &ptr, &columns, &num_columns );
641     msi_parse_line( &ptr, &types, &num_types );
642     msi_parse_line( &ptr, &labels, &num_labels );
643
644     if (num_columns != num_types)
645     {
646         r = ERROR_FUNCTION_FAILED;
647         goto done;
648     }
649
650     records = msi_alloc(sizeof(LPWSTR *));
651     if (!records)
652     {
653         r = ERROR_OUTOFMEMORY;
654         goto done;
655     }
656
657     /* read in the table records */
658     while (*ptr)
659     {
660         msi_parse_line( &ptr, &records[num_records], NULL );
661
662         num_records++;
663         temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
664         if (!temp_records)
665         {
666             r = ERROR_OUTOFMEMORY;
667             goto done;
668         }
669         records = temp_records;
670     }
671
672     if (!TABLE_Exists(db, labels[0]))
673     {
674         r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
675         if (r != ERROR_SUCCESS)
676         {
677             r = ERROR_FUNCTION_FAILED;
678             goto done;
679         }
680     }
681
682     r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records );
683
684 done:
685     msi_free(path);
686     msi_free(data);
687     msi_free(columns);
688     msi_free(types);
689     msi_free(labels);
690
691     for (i = 0; i < num_records; i++)
692         msi_free(records[i]);
693
694     msi_free(records);
695
696     return r;
697 }
698
699 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
700 {
701     MSIDATABASE *db;
702     UINT r;
703
704     TRACE("%lx %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
705
706     db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
707     if( !db )
708     {
709         IWineMsiRemoteDatabase *remote_database;
710
711         remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
712         if ( !remote_database )
713             return ERROR_INVALID_HANDLE;
714
715         IWineMsiRemoteDatabase_Release( remote_database );
716         WARN("MsiDatabaseImport not allowed during a custom action!\n");
717
718         return ERROR_SUCCESS;
719     }
720
721     r = MSI_DatabaseImport( db, szFolder, szFilename );
722     msiobj_release( &db->hdr );
723     return r;
724 }
725
726 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
727                LPCSTR szFolder, LPCSTR szFilename )
728 {
729     LPWSTR path = NULL, file = NULL;
730     UINT r = ERROR_OUTOFMEMORY;
731
732     TRACE("%lx %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
733
734     if( szFolder )
735     {
736         path = strdupAtoW( szFolder );
737         if( !path )
738             goto end;
739     }
740
741     if( szFilename )
742     {
743         file = strdupAtoW( szFilename );
744         if( !file )
745             goto end;
746     }
747
748     r = MsiDatabaseImportW( handle, path, file );
749
750 end:
751     msi_free( path );
752     msi_free( file );
753
754     return r;
755 }
756
757 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
758 {
759     UINT i, count, len, r = ERROR_SUCCESS;
760     const char *sep;
761     char *buffer;
762     DWORD sz;
763
764     len = 0x100;
765     buffer = msi_alloc( len );
766     if ( !buffer )
767         return ERROR_OUTOFMEMORY;
768
769     count = MSI_RecordGetFieldCount( row );
770     for ( i=start; i<=count; i++ )
771     {
772         sz = len;
773         r = MSI_RecordGetStringA( row, i, buffer, &sz );
774         if (r == ERROR_MORE_DATA)
775         {
776             char *p = msi_realloc( buffer, sz + 1 );
777             if (!p)
778                 break;
779             len = sz + 1;
780             buffer = p;
781         }
782         sz = len;
783         r = MSI_RecordGetStringA( row, i, buffer, &sz );
784         if (r != ERROR_SUCCESS)
785             break;
786
787         if (!WriteFile( handle, buffer, sz, &sz, NULL ))
788         {
789             r = ERROR_FUNCTION_FAILED;
790             break;
791         }
792
793         sep = (i < count) ? "\t" : "\r\n";
794         if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
795         {
796             r = ERROR_FUNCTION_FAILED;
797             break;
798         }
799     }
800     msi_free( buffer );
801     return r;
802 }
803
804 static UINT msi_export_row( MSIRECORD *row, void *arg )
805 {
806     return msi_export_record( arg, row, 1 );
807 }
808
809 static UINT msi_export_forcecodepage( HANDLE handle )
810 {
811     DWORD sz;
812
813     static const char data[] = "\r\n\r\n0\t_ForceCodepage\r\n";
814
815     FIXME("Read the codepage from the strings table!\n");
816
817     sz = lstrlenA(data) + 1;
818     if (!WriteFile(handle, data, sz, &sz, NULL))
819         return ERROR_FUNCTION_FAILED;
820
821     return ERROR_SUCCESS;
822 }
823
824 UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
825                LPCWSTR folder, LPCWSTR file )
826 {
827     static const WCHAR query[] = {
828         's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
829     static const WCHAR szbs[] = { '\\', 0 };
830     static const WCHAR forcecodepage[] = {
831         '_','F','o','r','c','e','C','o','d','e','p','a','g','e',0 };
832     MSIRECORD *rec = NULL;
833     MSIQUERY *view = NULL;
834     LPWSTR filename;
835     HANDLE handle;
836     UINT len, r;
837
838     TRACE("%p %s %s %s\n", db, debugstr_w(table),
839           debugstr_w(folder), debugstr_w(file) );
840
841     if( folder == NULL || file == NULL )
842         return ERROR_INVALID_PARAMETER;
843
844     len = lstrlenW(folder) + lstrlenW(file) + 2;
845     filename = msi_alloc(len * sizeof (WCHAR));
846     if (!filename)
847         return ERROR_OUTOFMEMORY;
848
849     lstrcpyW( filename, folder );
850     lstrcatW( filename, szbs );
851     lstrcatW( filename, file );
852
853     handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
854                           NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
855     msi_free( filename );
856     if (handle == INVALID_HANDLE_VALUE)
857         return ERROR_FUNCTION_FAILED;
858
859     if (!lstrcmpW( table, forcecodepage ))
860     {
861         r = msi_export_forcecodepage( handle );
862         goto done;
863     }
864
865     r = MSI_OpenQuery( db, &view, query, table );
866     if (r == ERROR_SUCCESS)
867     {
868         /* write out row 1, the column names */
869         r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
870         if (r == ERROR_SUCCESS)
871         {
872             msi_export_record( handle, rec, 1 );
873             msiobj_release( &rec->hdr );
874         }
875
876         /* write out row 2, the column types */
877         r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
878         if (r == ERROR_SUCCESS)
879         {
880             msi_export_record( handle, rec, 1 );
881             msiobj_release( &rec->hdr );
882         }
883
884         /* write out row 3, the table name + keys */
885         r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
886         if (r == ERROR_SUCCESS)
887         {
888             MSI_RecordSetStringW( rec, 0, table );
889             msi_export_record( handle, rec, 0 );
890             msiobj_release( &rec->hdr );
891         }
892
893         /* write out row 4 onwards, the data */
894         r = MSI_IterateRecords( view, 0, msi_export_row, handle );
895         msiobj_release( &view->hdr );
896     }
897
898 done:
899     CloseHandle( handle );
900     return r;
901 }
902
903 /***********************************************************************
904  * MsiExportDatabaseW        [MSI.@]
905  *
906  * Writes a file containing the table data as tab separated ASCII.
907  *
908  * The format is as follows:
909  *
910  * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
911  * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
912  * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
913  *
914  * Followed by the data, starting at row 1 with one row per line
915  *
916  * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
917  */
918 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
919                LPCWSTR szFolder, LPCWSTR szFilename )
920 {
921     MSIDATABASE *db;
922     UINT r;
923
924     TRACE("%lx %s %s %s\n", handle, debugstr_w(szTable),
925           debugstr_w(szFolder), debugstr_w(szFilename));
926
927     db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
928     if( !db )
929     {
930         IWineMsiRemoteDatabase *remote_database;
931
932         remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
933         if ( !remote_database )
934             return ERROR_INVALID_HANDLE;
935
936         IWineMsiRemoteDatabase_Release( remote_database );
937         WARN("MsiDatabaseExport not allowed during a custom action!\n");
938
939         return ERROR_SUCCESS;
940     }
941
942     r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
943     msiobj_release( &db->hdr );
944     return r;
945 }
946
947 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
948                LPCSTR szFolder, LPCSTR szFilename )
949 {
950     LPWSTR path = NULL, file = NULL, table = NULL;
951     UINT r = ERROR_OUTOFMEMORY;
952
953     TRACE("%lx %s %s %s\n", handle, debugstr_a(szTable),
954           debugstr_a(szFolder), debugstr_a(szFilename));
955
956     if( szTable )
957     {
958         table = strdupAtoW( szTable );
959         if( !table )
960             goto end;
961     }
962
963     if( szFolder )
964     {
965         path = strdupAtoW( szFolder );
966         if( !path )
967             goto end;
968     }
969
970     if( szFilename )
971     {
972         file = strdupAtoW( szFilename );
973         if( !file )
974             goto end;
975     }
976
977     r = MsiDatabaseExportW( handle, table, path, file );
978
979 end:
980     msi_free( table );
981     msi_free( path );
982     msi_free( file );
983
984     return r;
985 }
986
987 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
988 {
989     MSIDBSTATE ret = MSIDBSTATE_READ;
990     MSIDATABASE *db;
991
992     TRACE("%ld\n", handle);
993
994     db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
995     if( !db )
996     {
997         IWineMsiRemoteDatabase *remote_database;
998
999         remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1000         if ( !remote_database )
1001             return MSIDBSTATE_ERROR;
1002
1003         IWineMsiRemoteDatabase_Release( remote_database );
1004         WARN("MsiGetDatabaseState not allowed during a custom action!\n");
1005
1006         return MSIDBSTATE_READ;
1007     }
1008
1009     if (db->mode != MSIDBOPEN_READONLY )
1010         ret = MSIDBSTATE_WRITE;
1011     msiobj_release( &db->hdr );
1012
1013     return ret;
1014 }
1015
1016 typedef struct _msi_remote_database_impl {
1017     const IWineMsiRemoteDatabaseVtbl *lpVtbl;
1018     MSIHANDLE database;
1019     LONG refs;
1020 } msi_remote_database_impl;
1021
1022 static inline msi_remote_database_impl* mrd_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase* iface )
1023 {
1024     return (msi_remote_database_impl *)iface;
1025 }
1026
1027 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
1028                                           REFIID riid,LPVOID *ppobj)
1029 {
1030     if( IsEqualCLSID( riid, &IID_IUnknown ) ||
1031         IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
1032     {
1033         IUnknown_AddRef( iface );
1034         *ppobj = iface;
1035         return S_OK;
1036     }
1037
1038     return E_NOINTERFACE;
1039 }
1040
1041 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
1042 {
1043     msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1044
1045     return InterlockedIncrement( &This->refs );
1046 }
1047
1048 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
1049 {
1050     msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1051     ULONG r;
1052
1053     r = InterlockedDecrement( &This->refs );
1054     if (r == 0)
1055     {
1056         MsiCloseHandle( This->database );
1057         msi_free( This );
1058     }
1059     return r;
1060 }
1061
1062 static HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
1063                                              BSTR table, MSICONDITION *persistent )
1064 {
1065     msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1066     *persistent = MsiDatabaseIsTablePersistentW(This->database, (LPWSTR)table);
1067     return S_OK;
1068 }
1069
1070 static HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
1071                                           BSTR table, MSIHANDLE *keys )
1072 {
1073     msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1074     UINT r = MsiDatabaseGetPrimaryKeysW(This->database, (LPWSTR)table, keys);
1075     return HRESULT_FROM_WIN32(r);
1076 }
1077
1078 static HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
1079                                                 UINT updatecount, MSIHANDLE *suminfo )
1080 {
1081     msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1082     UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
1083     return HRESULT_FROM_WIN32(r);
1084 }
1085
1086 static HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
1087                                     BSTR query, MSIHANDLE *view )
1088 {
1089     msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1090     UINT r = MsiDatabaseOpenViewW(This->database, (LPWSTR)query, view);
1091     return HRESULT_FROM_WIN32(r);
1092 }
1093
1094 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
1095 {
1096     msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1097     This->database = handle;
1098     return S_OK;
1099 }
1100
1101 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
1102 {
1103     mrd_QueryInterface,
1104     mrd_AddRef,
1105     mrd_Release,
1106     mrd_IsTablePersistent,
1107     mrd_GetPrimaryKeys,
1108     mrd_GetSummaryInformation,
1109     mrd_OpenView,
1110     mrd_SetMsiHandle,
1111 };
1112
1113 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
1114 {
1115     msi_remote_database_impl *This;
1116
1117     This = msi_alloc( sizeof *This );
1118     if (!This)
1119         return E_OUTOFMEMORY;
1120
1121     This->lpVtbl = &msi_remote_database_vtbl;
1122     This->database = 0;
1123     This->refs = 1;
1124
1125     *ppObj = This;
1126
1127     return S_OK;
1128 }