mcicda: Rework MCI notification system.
[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 #include "query.h"
39
40 #include "initguid.h"
41
42 WINE_DEFAULT_DEBUG_CHANNEL(msi);
43
44 /*
45  *  .MSI  file format
46  *
47  *  An .msi file is a structured storage file.
48  *  It contains a number of streams.
49  *  A stream for each table in the database.
50  *  Two streams for the string table in the database.
51  *  Any binary data in a table is a reference to a stream.
52  */
53
54 #define IS_INTMSIDBOPEN(x)      (((ULONG_PTR)(x) >> 16) == 0)
55
56 typedef struct tagMSITRANSFORM {
57     struct list entry;
58     IStorage *stg;
59 } MSITRANSFORM;
60
61 typedef struct tagMSISTREAM {
62     struct list entry;
63     IStream *stm;
64 } MSISTREAM;
65
66 static UINT find_open_stream( MSIDATABASE *db, LPCWSTR name, IStream **stm )
67 {
68     MSISTREAM *stream;
69
70     LIST_FOR_EACH_ENTRY( stream, &db->streams, MSISTREAM, entry )
71     {
72         HRESULT r;
73         STATSTG stat;
74
75         r = IStream_Stat( stream->stm, &stat, 0 );
76         if( FAILED( r ) )
77         {
78             WARN("failed to stat stream r = %08x!\n", r);
79             continue;
80         }
81
82         if( !lstrcmpW( name, stat.pwcsName ) )
83         {
84             TRACE("found %s\n", debugstr_w(name));
85             *stm = stream->stm;
86             CoTaskMemFree( stat.pwcsName );
87             return ERROR_SUCCESS;
88         }
89
90         CoTaskMemFree( stat.pwcsName );
91     }
92
93     return ERROR_FUNCTION_FAILED;
94 }
95
96 static UINT clone_open_stream( MSIDATABASE *db, LPCWSTR name, IStream **stm )
97 {
98     IStream *stream;
99
100     if (find_open_stream( db, name, &stream ) == ERROR_SUCCESS)
101     {
102         HRESULT r;
103         LARGE_INTEGER pos;
104
105         r = IStream_Clone( stream, stm );
106         if( FAILED( r ) )
107         {
108             WARN("failed to clone stream r = %08x!\n", r);
109             return ERROR_FUNCTION_FAILED;
110         }
111
112         pos.QuadPart = 0;
113         r = IStream_Seek( *stm, pos, STREAM_SEEK_SET, NULL );
114         if( FAILED( r ) )
115         {
116             IStream_Release( *stm );
117             return ERROR_FUNCTION_FAILED;
118         }
119
120         return ERROR_SUCCESS;
121     }
122
123     return ERROR_FUNCTION_FAILED;
124 }
125
126 UINT db_get_raw_stream( MSIDATABASE *db, LPCWSTR stname, IStream **stm )
127 {
128     HRESULT r;
129     WCHAR decoded[MAX_STREAM_NAME_LEN];
130
131     decode_streamname( stname, decoded );
132     TRACE("%s -> %s\n", debugstr_w(stname), debugstr_w(decoded));
133
134     if (clone_open_stream( db, stname, stm ) == ERROR_SUCCESS)
135         return ERROR_SUCCESS;
136
137     r = IStorage_OpenStream( db->storage, stname, NULL,
138                              STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
139     if( FAILED( r ) )
140     {
141         MSITRANSFORM *transform;
142
143         LIST_FOR_EACH_ENTRY( transform, &db->transforms, MSITRANSFORM, entry )
144         {
145             r = IStorage_OpenStream( transform->stg, stname, NULL,
146                                      STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
147             if (SUCCEEDED(r))
148                 break;
149         }
150     }
151
152     if( SUCCEEDED(r) )
153     {
154         MSISTREAM *stream;
155
156         stream = msi_alloc( sizeof(MSISTREAM) );
157         if( !stream )
158             return ERROR_NOT_ENOUGH_MEMORY;
159
160         stream->stm = *stm;
161         IStream_AddRef( *stm );
162         list_add_tail( &db->streams, &stream->entry );
163     }
164
165     return SUCCEEDED(r) ? ERROR_SUCCESS : ERROR_FUNCTION_FAILED;
166 }
167
168 static void free_transforms( MSIDATABASE *db )
169 {
170     while( !list_empty( &db->transforms ) )
171     {
172         MSITRANSFORM *t = LIST_ENTRY( list_head( &db->transforms ),
173                                       MSITRANSFORM, entry );
174         list_remove( &t->entry );
175         IStorage_Release( t->stg );
176         msi_free( t );
177     }
178 }
179
180 void db_destroy_stream( MSIDATABASE *db, LPCWSTR stname )
181 {
182     MSISTREAM *stream, *stream2;
183
184     LIST_FOR_EACH_ENTRY_SAFE( stream, stream2, &db->streams, MSISTREAM, entry )
185     {
186         HRESULT r;
187         STATSTG stat;
188
189         r = IStream_Stat( stream->stm, &stat, 0 );
190         if (FAILED(r))
191         {
192             WARN("failed to stat stream r = %08x\n", r);
193             continue;
194         }
195
196         if (!strcmpW( stname, stat.pwcsName ))
197         {
198             TRACE("destroying %s\n", debugstr_w(stname));
199
200             list_remove( &stream->entry );
201             IStream_Release( stream->stm );
202             msi_free( stream );
203             IStorage_DestroyElement( db->storage, stname );
204             CoTaskMemFree( stat.pwcsName );
205             break;
206         }
207         CoTaskMemFree( stat.pwcsName );
208     }
209 }
210
211 static void free_streams( MSIDATABASE *db )
212 {
213     while( !list_empty( &db->streams ) )
214     {
215         MSISTREAM *s = LIST_ENTRY( list_head( &db->streams ),
216                                    MSISTREAM, entry );
217         list_remove( &s->entry );
218         IStream_Release( s->stm );
219         msi_free( s );
220     }
221 }
222
223 void append_storage_to_db( MSIDATABASE *db, IStorage *stg )
224 {
225     MSITRANSFORM *t;
226
227     t = msi_alloc( sizeof *t );
228     t->stg = stg;
229     IStorage_AddRef( stg );
230     list_add_head( &db->transforms, &t->entry );
231
232     /* the transform may add or replace streams */
233     free_streams( db );
234 }
235
236 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
237 {
238     MSIDATABASE *db = (MSIDATABASE *) arg;
239
240     msi_free(db->path);
241     free_cached_tables( db );
242     free_streams( db );
243     free_transforms( db );
244     msi_destroy_stringtable( db->strings );
245     IStorage_Release( db->storage );
246     if (db->deletefile)
247     {
248         DeleteFileW( db->deletefile );
249         msi_free( db->deletefile );
250     }
251     if (db->localfile)
252     {
253         DeleteFileW( db->localfile );
254         msi_free( db->localfile );
255     }
256 }
257
258 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
259 {
260     IStorage *stg = NULL;
261     HRESULT r;
262     MSIDATABASE *db = NULL;
263     UINT ret = ERROR_FUNCTION_FAILED;
264     LPCWSTR szMode, save_path;
265     STATSTG stat;
266     BOOL created = FALSE, patch = FALSE;
267     WCHAR path[MAX_PATH];
268
269     static const WCHAR szTables[]  = { '_','T','a','b','l','e','s',0 };
270
271     TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
272
273     if( !pdb )
274         return ERROR_INVALID_PARAMETER;
275
276     if (szPersist - MSIDBOPEN_PATCHFILE >= MSIDBOPEN_READONLY &&
277         szPersist - MSIDBOPEN_PATCHFILE <= MSIDBOPEN_CREATEDIRECT)
278     {
279         TRACE("Database is a patch\n");
280         szPersist -= MSIDBOPEN_PATCHFILE;
281         patch = TRUE;
282     }
283
284     save_path = szDBPath;
285     szMode = szPersist;
286     if( !IS_INTMSIDBOPEN(szPersist) )
287     {
288         if (!CopyFileW( szDBPath, szPersist, FALSE ))
289             return ERROR_OPEN_FAILED;
290
291         szDBPath = szPersist;
292         szPersist = MSIDBOPEN_TRANSACT;
293         created = TRUE;
294     }
295
296     if( szPersist == MSIDBOPEN_READONLY )
297     {
298         r = StgOpenStorage( szDBPath, NULL,
299               STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
300     }
301     else if( szPersist == MSIDBOPEN_CREATE || szPersist == MSIDBOPEN_CREATEDIRECT )
302     {
303         /* FIXME: MSIDBOPEN_CREATE should case STGM_TRANSACTED flag to be
304          * used here: */
305         r = StgCreateDocfile( szDBPath,
306               STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg);
307         if( r == ERROR_SUCCESS )
308         {
309             IStorage_SetClass( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
310             /* create the _Tables stream */
311             r = write_stream_data(stg, szTables, NULL, 0, TRUE);
312             if (SUCCEEDED(r))
313                 r = msi_init_string_table( stg );
314         }
315         created = TRUE;
316     }
317     else if( szPersist == MSIDBOPEN_TRANSACT )
318     {
319         /* FIXME: MSIDBOPEN_TRANSACT should case STGM_TRANSACTED flag to be
320          * used here: */
321         r = StgOpenStorage( szDBPath, NULL,
322               STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
323     }
324     else if( szPersist == MSIDBOPEN_DIRECT )
325     {
326         r = StgOpenStorage( szDBPath, NULL,
327               STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
328     }
329     else
330     {
331         ERR("unknown flag %p\n",szPersist);
332         return ERROR_INVALID_PARAMETER;
333     }
334
335     if( FAILED( r ) || !stg )
336     {
337         FIXME("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
338         return ERROR_FUNCTION_FAILED;
339     }
340
341     r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
342     if( FAILED( r ) )
343     {
344         FIXME("Failed to stat storage\n");
345         goto end;
346     }
347
348     if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
349          !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) &&
350          !IsEqualGUID( &stat.clsid, &CLSID_MsiTransform ) )
351     {
352         ERR("storage GUID is not a MSI database GUID %s\n",
353              debugstr_guid(&stat.clsid) );
354         goto end;
355     }
356
357     if ( patch && !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) )
358     {
359         ERR("storage GUID is not the MSI patch GUID %s\n",
360              debugstr_guid(&stat.clsid) );
361         ret = ERROR_OPEN_FAILED;
362         goto end;
363     }
364
365     db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
366                               MSI_CloseDatabase );
367     if( !db )
368     {
369         FIXME("Failed to allocate a handle\n");
370         goto end;
371     }
372
373     if (!strchrW( save_path, '\\' ))
374     {
375         GetCurrentDirectoryW( MAX_PATH, path );
376         lstrcatW( path, szBackSlash );
377         lstrcatW( path, save_path );
378     }
379     else
380         lstrcpyW( path, save_path );
381
382     db->path = strdupW( path );
383
384     if( TRACE_ON( msi ) )
385         enum_stream_names( stg );
386
387     db->storage = stg;
388     db->mode = szMode;
389     if (created)
390         db->deletefile = strdupW( szDBPath );
391     list_init( &db->tables );
392     list_init( &db->transforms );
393     list_init( &db->streams );
394
395     db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
396     if( !db->strings )
397         goto end;
398
399     ret = ERROR_SUCCESS;
400
401     msiobj_addref( &db->hdr );
402     IStorage_AddRef( stg );
403     *pdb = db;
404
405 end:
406     if( db )
407         msiobj_release( &db->hdr );
408     if( stg )
409         IStorage_Release( stg );
410
411     return ret;
412 }
413
414 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
415 {
416     MSIDATABASE *db;
417     UINT ret;
418
419     TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
420
421     ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
422     if( ret == ERROR_SUCCESS )
423     {
424         *phDB = alloc_msihandle( &db->hdr );
425         if (! *phDB)
426             ret = ERROR_NOT_ENOUGH_MEMORY;
427         msiobj_release( &db->hdr );
428     }
429
430     return ret;
431 }
432
433 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
434 {
435     HRESULT r = ERROR_FUNCTION_FAILED;
436     LPWSTR szwDBPath = NULL, szwPersist = NULL;
437
438     TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
439
440     if( szDBPath )
441     {
442         szwDBPath = strdupAtoW( szDBPath );
443         if( !szwDBPath )
444             goto end;
445     }
446
447     if( !IS_INTMSIDBOPEN(szPersist) )
448     {
449         szwPersist = strdupAtoW( szPersist );
450         if( !szwPersist )
451             goto end;
452     }
453     else
454         szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
455
456     r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
457
458 end:
459     if( !IS_INTMSIDBOPEN(szPersist) )
460         msi_free( szwPersist );
461     msi_free( szwDBPath );
462
463     return r;
464 }
465
466 static LPWSTR msi_read_text_archive(LPCWSTR path)
467 {
468     HANDLE file;
469     LPSTR data = NULL;
470     LPWSTR wdata = NULL;
471     DWORD read, size = 0;
472
473     file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
474     if (file == INVALID_HANDLE_VALUE)
475         return NULL;
476
477     size = GetFileSize( file, NULL );
478     data = msi_alloc( size + 1 );
479     if (!data)
480         goto done;
481
482     if (!ReadFile( file, data, size, &read, NULL ))
483         goto done;
484
485     data[size] = '\0';
486     wdata = strdupAtoW( data );
487
488 done:
489     CloseHandle( file );
490     msi_free( data );
491     return wdata;
492 }
493
494 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries)
495 {
496     LPWSTR ptr = *line, save;
497     DWORD i, count = 1;
498
499     *entries = NULL;
500
501     /* stay on this line */
502     while (*ptr && *ptr != '\n')
503     {
504         /* entries are separated by tabs */
505         if (*ptr == '\t')
506             count++;
507
508         ptr++;
509     }
510
511     *entries = msi_alloc(count * sizeof(LPWSTR));
512     if (!*entries)
513         return;
514
515     /* store pointers into the data */
516     for (i = 0, ptr = *line; i < count; i++)
517     {
518         while (*ptr && *ptr == '\r') ptr++;
519         save = ptr;
520
521         while (*ptr && *ptr != '\t' && *ptr != '\n' && *ptr != '\r') ptr++;
522
523         /* NULL-separate the data */
524         if (*ptr == '\n' || *ptr == '\r')
525         {
526             while (*ptr == '\n' || *ptr == '\r')
527                 *(ptr++) = '\0';
528         }
529         else if (*ptr)
530             *ptr++ = '\0';
531
532         (*entries)[i] = save;
533     }
534
535     /* move to the next line if there's more, else EOF */
536     *line = ptr;
537
538     if (num_entries)
539         *num_entries = count;
540 }
541
542 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
543 {
544     LPWSTR prelude;
545     DWORD size;
546
547     static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
548
549     size = sizeof(create_fmt)/sizeof(create_fmt[0]) + lstrlenW(table) - 2;
550     prelude = msi_alloc(size * sizeof(WCHAR));
551     if (!prelude)
552         return NULL;
553
554     sprintfW(prelude, create_fmt, table);
555     return prelude;
556 }
557
558 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
559 {
560     LPWSTR columns, p;
561     LPCWSTR type;
562     DWORD sql_size = 1, i, len;
563     WCHAR expanded[128], *ptr;
564     WCHAR size[10], comma[2], extra[30];
565
566     static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
567     static const WCHAR size_fmt[] = {'(','%','s',')',0};
568     static const WCHAR type_char[] = {'C','H','A','R',0};
569     static const WCHAR type_int[] = {'I','N','T',0};
570     static const WCHAR type_long[] = {'L','O','N','G',0};
571     static const WCHAR type_object[] = {'O','B','J','E','C','T',0};
572     static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
573     static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
574
575     columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
576     if (!columns)
577         return NULL;
578
579     for (i = 0; i < num_columns; i++)
580     {
581         type = NULL;
582         comma[1] = size[0] = extra[0] = '\0';
583
584         if (i == num_columns - 1)
585             comma[0] = '\0';
586         else
587             comma[0] = ',';
588
589         ptr = &types[i][1];
590         len = atolW(ptr);
591         extra[0] = '\0';
592
593         switch (types[i][0])
594         {
595             case 'l':
596                 lstrcpyW(extra, type_notnull);
597             case 'L':
598                 lstrcatW(extra, localizable);
599                 type = type_char;
600                 sprintfW(size, size_fmt, ptr);
601                 break;
602             case 's':
603                 lstrcpyW(extra, type_notnull);
604             case 'S':
605                 type = type_char;
606                 sprintfW(size, size_fmt, ptr);
607                 break;
608             case 'i':
609                 lstrcpyW(extra, type_notnull);
610             case 'I':
611                 if (len <= 2)
612                     type = type_int;
613                 else if (len == 4)
614                     type = type_long;
615                 else
616                 {
617                     WARN("invalid int width %u\n", len);
618                     msi_free(columns);
619                     return NULL;
620                 }
621                 break;
622             case 'v':
623                 lstrcpyW(extra, type_notnull);
624             case 'V':
625                 type = type_object;
626                 break;
627             default:
628                 ERR("Unknown type: %c\n", types[i][0]);
629                 msi_free(columns);
630                 return NULL;
631         }
632
633         sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
634         sql_size += lstrlenW(expanded);
635
636         p = msi_realloc(columns, sql_size * sizeof(WCHAR));
637         if (!p)
638         {
639             msi_free(columns);
640             return NULL;
641         }
642         columns = p;
643
644         lstrcatW(columns, expanded);
645     }
646
647     return columns;
648 }
649
650 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
651 {
652     LPWSTR postlude, keys, ptr;
653     DWORD size, key_size, i;
654
655     static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
656     static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
657
658     for (i = 0, size = 1; i < num_keys; i++)
659         size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
660
661     keys = msi_alloc(size * sizeof(WCHAR));
662     if (!keys)
663         return NULL;
664
665     for (i = 0, ptr = keys; i < num_keys; i++)
666     {
667         key_size = lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) -2;
668         sprintfW(ptr, key_fmt, primary_keys[i]);
669         ptr += key_size;
670     }
671
672     /* remove final ', ' */
673     *(ptr - 2) = '\0';
674
675     size = lstrlenW(postlude_fmt) + size - 1;
676     postlude = msi_alloc(size * sizeof(WCHAR));
677     if (!postlude)
678         goto done;
679
680     sprintfW(postlude, postlude_fmt, keys);
681
682 done:
683     msi_free(keys);
684     return postlude;
685 }
686
687 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
688 {
689     UINT r = ERROR_OUTOFMEMORY;
690     DWORD size;
691     MSIQUERY *view;
692     LPWSTR create_sql = NULL;
693     LPWSTR prelude, columns_sql, postlude;
694
695     prelude = msi_build_createsql_prelude(labels[0]);
696     columns_sql = msi_build_createsql_columns(columns, types, num_columns);
697     postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
698
699     if (!prelude || !columns_sql || !postlude)
700         goto done;
701
702     size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
703     create_sql = msi_alloc(size * sizeof(WCHAR));
704     if (!create_sql)
705         goto done;
706
707     lstrcpyW(create_sql, prelude);
708     lstrcatW(create_sql, columns_sql);
709     lstrcatW(create_sql, postlude);
710
711     r = MSI_DatabaseOpenViewW( db, create_sql, &view );
712     if (r != ERROR_SUCCESS)
713         goto done;
714
715     r = MSI_ViewExecute(view, NULL);
716     MSI_ViewClose(view);
717     msiobj_release(&view->hdr);
718
719 done:
720     msi_free(prelude);
721     msi_free(columns_sql);
722     msi_free(postlude);
723     msi_free(create_sql);
724     return r;
725 }
726
727 static LPWSTR msi_import_stream_filename(LPCWSTR path, LPCWSTR name)
728 {
729     DWORD len;
730     LPWSTR fullname, ptr;
731
732     len = lstrlenW(path) + lstrlenW(name) + 1;
733     fullname = msi_alloc(len*sizeof(WCHAR));
734     if (!fullname)
735        return NULL;
736
737     lstrcpyW( fullname, path );
738
739     /* chop off extension from path */
740     ptr = strrchrW(fullname, '.');
741     if (!ptr)
742     {
743         msi_free (fullname);
744         return NULL;
745     }
746     *ptr++ = '\\';
747     lstrcpyW( ptr, name );
748     return fullname;
749 }
750
751 static UINT construct_record(DWORD num_columns, LPWSTR *types,
752                              LPWSTR *data, LPWSTR path, MSIRECORD **rec)
753 {
754     UINT i;
755
756     *rec = MSI_CreateRecord(num_columns);
757     if (!*rec)
758         return ERROR_OUTOFMEMORY;
759
760     for (i = 0; i < num_columns; i++)
761     {
762         switch (types[i][0])
763         {
764             case 'L': case 'l': case 'S': case 's':
765                 MSI_RecordSetStringW(*rec, i + 1, data[i]);
766                 break;
767             case 'I': case 'i':
768                 if (*data[i])
769                     MSI_RecordSetInteger(*rec, i + 1, atoiW(data[i]));
770                 break;
771             case 'V': case 'v':
772                 if (*data[i])
773                 {
774                     UINT r;
775                     LPWSTR file = msi_import_stream_filename(path, data[i]);
776                     if (!file)
777                         return ERROR_FUNCTION_FAILED;
778
779                     r = MSI_RecordSetStreamFromFileW(*rec, i + 1, file);
780                     msi_free (file);
781                     if (r != ERROR_SUCCESS)
782                         return ERROR_FUNCTION_FAILED;
783                 }
784                 break;
785             default:
786                 ERR("Unhandled column type: %c\n", types[i][0]);
787                 msiobj_release(&(*rec)->hdr);
788                 return ERROR_FUNCTION_FAILED;
789         }
790     }
791
792     return ERROR_SUCCESS;
793 }
794
795 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
796                                      LPWSTR *labels, LPWSTR **records,
797                                      int num_columns, int num_records,
798                                      LPWSTR path)
799 {
800     UINT r;
801     int i;
802     MSIQUERY *view;
803     MSIRECORD *rec;
804
805     static const WCHAR select[] = {
806         'S','E','L','E','C','T',' ','*',' ',
807         'F','R','O','M',' ','`','%','s','`',0
808     };
809
810     r = MSI_OpenQuery(db, &view, select, labels[0]);
811     if (r != ERROR_SUCCESS)
812         return r;
813
814     while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
815     {
816         r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
817         msiobj_release(&rec->hdr);
818         if (r != ERROR_SUCCESS)
819             goto done;
820     }
821
822     for (i = 0; i < num_records; i++)
823     {
824         r = construct_record(num_columns, types, records[i], path, &rec);
825         if (r != ERROR_SUCCESS)
826             goto done;
827
828         r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
829         if (r != ERROR_SUCCESS)
830         {
831             msiobj_release(&rec->hdr);
832             goto done;
833         }
834
835         msiobj_release(&rec->hdr);
836     }
837
838 done:
839     msiobj_release(&view->hdr);
840     return r;
841 }
842
843 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
844 {
845     UINT r;
846     DWORD len, i;
847     DWORD num_labels, num_types;
848     DWORD num_columns, num_records = 0;
849     LPWSTR *columns, *types, *labels;
850     LPWSTR path, ptr, data;
851     LPWSTR **records = NULL;
852     LPWSTR **temp_records;
853
854     static const WCHAR suminfo[] =
855         {'_','S','u','m','m','a','r','y','I','n','f','o','r','m','a','t','i','o','n',0};
856
857     TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
858
859     if( folder == NULL || file == NULL )
860         return ERROR_INVALID_PARAMETER;
861
862     len = lstrlenW(folder) + lstrlenW(szBackSlash) + lstrlenW(file) + 1;
863     path = msi_alloc( len * sizeof(WCHAR) );
864     if (!path)
865         return ERROR_OUTOFMEMORY;
866
867     lstrcpyW( path, folder );
868     lstrcatW( path, szBackSlash );
869     lstrcatW( path, file );
870
871     data = msi_read_text_archive( path );
872
873     ptr = data;
874     msi_parse_line( &ptr, &columns, &num_columns );
875     msi_parse_line( &ptr, &types, &num_types );
876     msi_parse_line( &ptr, &labels, &num_labels );
877
878     if (num_columns != num_types)
879     {
880         r = ERROR_FUNCTION_FAILED;
881         goto done;
882     }
883
884     records = msi_alloc(sizeof(LPWSTR *));
885     if (!records)
886     {
887         r = ERROR_OUTOFMEMORY;
888         goto done;
889     }
890
891     /* read in the table records */
892     while (*ptr)
893     {
894         msi_parse_line( &ptr, &records[num_records], NULL );
895
896         num_records++;
897         temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
898         if (!temp_records)
899         {
900             r = ERROR_OUTOFMEMORY;
901             goto done;
902         }
903         records = temp_records;
904     }
905
906     if (!strcmpW(labels[0], suminfo))
907     {
908         r = msi_add_suminfo( db, records, num_records, num_columns );
909         if (r != ERROR_SUCCESS)
910         {
911             r = ERROR_FUNCTION_FAILED;
912             goto done;
913         }
914     }
915     else
916     {
917         if (!TABLE_Exists(db, labels[0]))
918         {
919             r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
920             if (r != ERROR_SUCCESS)
921             {
922                 r = ERROR_FUNCTION_FAILED;
923                 goto done;
924             }
925         }
926
927         r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records, path );
928     }
929
930 done:
931     msi_free(path);
932     msi_free(data);
933     msi_free(columns);
934     msi_free(types);
935     msi_free(labels);
936
937     for (i = 0; i < num_records; i++)
938         msi_free(records[i]);
939
940     msi_free(records);
941
942     return r;
943 }
944
945 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
946 {
947     MSIDATABASE *db;
948     UINT r;
949
950     TRACE("%x %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
951
952     db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
953     if( !db )
954     {
955         IWineMsiRemoteDatabase *remote_database;
956
957         remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
958         if ( !remote_database )
959             return ERROR_INVALID_HANDLE;
960
961         IWineMsiRemoteDatabase_Release( remote_database );
962         WARN("MsiDatabaseImport not allowed during a custom action!\n");
963
964         return ERROR_SUCCESS;
965     }
966
967     r = MSI_DatabaseImport( db, szFolder, szFilename );
968     msiobj_release( &db->hdr );
969     return r;
970 }
971
972 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
973                LPCSTR szFolder, LPCSTR szFilename )
974 {
975     LPWSTR path = NULL, file = NULL;
976     UINT r = ERROR_OUTOFMEMORY;
977
978     TRACE("%x %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
979
980     if( szFolder )
981     {
982         path = strdupAtoW( szFolder );
983         if( !path )
984             goto end;
985     }
986
987     if( szFilename )
988     {
989         file = strdupAtoW( szFilename );
990         if( !file )
991             goto end;
992     }
993
994     r = MsiDatabaseImportW( handle, path, file );
995
996 end:
997     msi_free( path );
998     msi_free( file );
999
1000     return r;
1001 }
1002
1003 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
1004 {
1005     UINT i, count, len, r = ERROR_SUCCESS;
1006     const char *sep;
1007     char *buffer;
1008     DWORD sz;
1009
1010     len = 0x100;
1011     buffer = msi_alloc( len );
1012     if ( !buffer )
1013         return ERROR_OUTOFMEMORY;
1014
1015     count = MSI_RecordGetFieldCount( row );
1016     for ( i=start; i<=count; i++ )
1017     {
1018         sz = len;
1019         r = MSI_RecordGetStringA( row, i, buffer, &sz );
1020         if (r == ERROR_MORE_DATA)
1021         {
1022             char *p = msi_realloc( buffer, sz + 1 );
1023             if (!p)
1024                 break;
1025             len = sz + 1;
1026             buffer = p;
1027         }
1028         sz = len;
1029         r = MSI_RecordGetStringA( row, i, buffer, &sz );
1030         if (r != ERROR_SUCCESS)
1031             break;
1032
1033         if (!WriteFile( handle, buffer, sz, &sz, NULL ))
1034         {
1035             r = ERROR_FUNCTION_FAILED;
1036             break;
1037         }
1038
1039         sep = (i < count) ? "\t" : "\r\n";
1040         if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
1041         {
1042             r = ERROR_FUNCTION_FAILED;
1043             break;
1044         }
1045     }
1046     msi_free( buffer );
1047     return r;
1048 }
1049
1050 static UINT msi_export_row( MSIRECORD *row, void *arg )
1051 {
1052     return msi_export_record( arg, row, 1 );
1053 }
1054
1055 static UINT msi_export_forcecodepage( HANDLE handle )
1056 {
1057     DWORD sz;
1058
1059     static const char data[] = "\r\n\r\n0\t_ForceCodepage\r\n";
1060
1061     FIXME("Read the codepage from the strings table!\n");
1062
1063     sz = lstrlenA(data) + 1;
1064     if (!WriteFile(handle, data, sz, &sz, NULL))
1065         return ERROR_FUNCTION_FAILED;
1066
1067     return ERROR_SUCCESS;
1068 }
1069
1070 static UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
1071                LPCWSTR folder, LPCWSTR file )
1072 {
1073     static const WCHAR query[] = {
1074         's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
1075     static const WCHAR forcecodepage[] = {
1076         '_','F','o','r','c','e','C','o','d','e','p','a','g','e',0 };
1077     MSIRECORD *rec = NULL;
1078     MSIQUERY *view = NULL;
1079     LPWSTR filename;
1080     HANDLE handle;
1081     UINT len, r;
1082
1083     TRACE("%p %s %s %s\n", db, debugstr_w(table),
1084           debugstr_w(folder), debugstr_w(file) );
1085
1086     if( folder == NULL || file == NULL )
1087         return ERROR_INVALID_PARAMETER;
1088
1089     len = lstrlenW(folder) + lstrlenW(file) + 2;
1090     filename = msi_alloc(len * sizeof (WCHAR));
1091     if (!filename)
1092         return ERROR_OUTOFMEMORY;
1093
1094     lstrcpyW( filename, folder );
1095     lstrcatW( filename, szBackSlash );
1096     lstrcatW( filename, file );
1097
1098     handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
1099                           NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
1100     msi_free( filename );
1101     if (handle == INVALID_HANDLE_VALUE)
1102         return ERROR_FUNCTION_FAILED;
1103
1104     if (!lstrcmpW( table, forcecodepage ))
1105     {
1106         r = msi_export_forcecodepage( handle );
1107         goto done;
1108     }
1109
1110     r = MSI_OpenQuery( db, &view, query, table );
1111     if (r == ERROR_SUCCESS)
1112     {
1113         /* write out row 1, the column names */
1114         r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
1115         if (r == ERROR_SUCCESS)
1116         {
1117             msi_export_record( handle, rec, 1 );
1118             msiobj_release( &rec->hdr );
1119         }
1120
1121         /* write out row 2, the column types */
1122         r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
1123         if (r == ERROR_SUCCESS)
1124         {
1125             msi_export_record( handle, rec, 1 );
1126             msiobj_release( &rec->hdr );
1127         }
1128
1129         /* write out row 3, the table name + keys */
1130         r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
1131         if (r == ERROR_SUCCESS)
1132         {
1133             MSI_RecordSetStringW( rec, 0, table );
1134             msi_export_record( handle, rec, 0 );
1135             msiobj_release( &rec->hdr );
1136         }
1137
1138         /* write out row 4 onwards, the data */
1139         r = MSI_IterateRecords( view, 0, msi_export_row, handle );
1140         msiobj_release( &view->hdr );
1141     }
1142
1143 done:
1144     CloseHandle( handle );
1145     return r;
1146 }
1147
1148 /***********************************************************************
1149  * MsiExportDatabaseW        [MSI.@]
1150  *
1151  * Writes a file containing the table data as tab separated ASCII.
1152  *
1153  * The format is as follows:
1154  *
1155  * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
1156  * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
1157  * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
1158  *
1159  * Followed by the data, starting at row 1 with one row per line
1160  *
1161  * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
1162  */
1163 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
1164                LPCWSTR szFolder, LPCWSTR szFilename )
1165 {
1166     MSIDATABASE *db;
1167     UINT r;
1168
1169     TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
1170           debugstr_w(szFolder), debugstr_w(szFilename));
1171
1172     db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1173     if( !db )
1174     {
1175         IWineMsiRemoteDatabase *remote_database;
1176
1177         remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1178         if ( !remote_database )
1179             return ERROR_INVALID_HANDLE;
1180
1181         IWineMsiRemoteDatabase_Release( remote_database );
1182         WARN("MsiDatabaseExport not allowed during a custom action!\n");
1183
1184         return ERROR_SUCCESS;
1185     }
1186
1187     r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
1188     msiobj_release( &db->hdr );
1189     return r;
1190 }
1191
1192 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
1193                LPCSTR szFolder, LPCSTR szFilename )
1194 {
1195     LPWSTR path = NULL, file = NULL, table = NULL;
1196     UINT r = ERROR_OUTOFMEMORY;
1197
1198     TRACE("%x %s %s %s\n", handle, debugstr_a(szTable),
1199           debugstr_a(szFolder), debugstr_a(szFilename));
1200
1201     if( szTable )
1202     {
1203         table = strdupAtoW( szTable );
1204         if( !table )
1205             goto end;
1206     }
1207
1208     if( szFolder )
1209     {
1210         path = strdupAtoW( szFolder );
1211         if( !path )
1212             goto end;
1213     }
1214
1215     if( szFilename )
1216     {
1217         file = strdupAtoW( szFilename );
1218         if( !file )
1219             goto end;
1220     }
1221
1222     r = MsiDatabaseExportW( handle, table, path, file );
1223
1224 end:
1225     msi_free( table );
1226     msi_free( path );
1227     msi_free( file );
1228
1229     return r;
1230 }
1231
1232 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1233                               LPCSTR szTableName)
1234 {
1235     UINT r;
1236     LPWSTR table;
1237
1238     TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1239           debugstr_a(szTableName));
1240
1241     table = strdupAtoW(szTableName);
1242     r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1243
1244     msi_free(table);
1245     return r;
1246 }
1247
1248 typedef struct _tagMERGETABLE
1249 {
1250     struct list entry;
1251     struct list rows;
1252     LPWSTR name;
1253     DWORD numconflicts;
1254     LPWSTR *columns;
1255     DWORD numcolumns;
1256     LPWSTR *types;
1257     DWORD numtypes;
1258     LPWSTR *labels;
1259     DWORD numlabels;
1260 } MERGETABLE;
1261
1262 typedef struct _tagMERGEROW
1263 {
1264     struct list entry;
1265     MSIRECORD *data;
1266 } MERGEROW;
1267
1268 typedef struct _tagMERGEDATA
1269 {
1270     MSIDATABASE *db;
1271     MSIDATABASE *merge;
1272     MERGETABLE *curtable;
1273     MSIQUERY *curview;
1274     struct list *tabledata;
1275 } MERGEDATA;
1276
1277 static BOOL merge_type_match(LPCWSTR type1, LPCWSTR type2)
1278 {
1279     if (((type1[0] == 'l') || (type1[0] == 's')) &&
1280         ((type2[0] == 'l') || (type2[0] == 's')))
1281         return TRUE;
1282
1283     if (((type1[0] == 'L') || (type1[0] == 'S')) &&
1284         ((type2[0] == 'L') || (type2[0] == 'S')))
1285         return TRUE;
1286
1287     return !lstrcmpW(type1, type2);
1288 }
1289
1290 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1291 {
1292     MSIRECORD *dbrec, *mergerec;
1293     UINT r, i, count;
1294
1295     r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1296     if (r != ERROR_SUCCESS)
1297         return r;
1298
1299     r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1300     if (r != ERROR_SUCCESS)
1301         return r;
1302
1303     count = MSI_RecordGetFieldCount(dbrec);
1304     for (i = 1; i <= count; i++)
1305     {
1306         if (!MSI_RecordGetString(mergerec, i))
1307             break;
1308
1309         if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1310                      MSI_RecordGetString(mergerec, i)))
1311         {
1312             r = ERROR_DATATYPE_MISMATCH;
1313             goto done;
1314         }
1315     }
1316
1317     msiobj_release(&dbrec->hdr);
1318     msiobj_release(&mergerec->hdr);
1319     dbrec = mergerec = NULL;
1320
1321     r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_TYPES, &dbrec);
1322     if (r != ERROR_SUCCESS)
1323         return r;
1324
1325     r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1326     if (r != ERROR_SUCCESS)
1327         return r;
1328
1329     count = MSI_RecordGetFieldCount(dbrec);
1330     for (i = 1; i <= count; i++)
1331     {
1332         if (!MSI_RecordGetString(mergerec, i))
1333             break;
1334
1335         if (!merge_type_match(MSI_RecordGetString(dbrec, i),
1336                      MSI_RecordGetString(mergerec, i)))
1337         {
1338             r = ERROR_DATATYPE_MISMATCH;
1339             break;
1340         }
1341     }
1342
1343 done:
1344     msiobj_release(&dbrec->hdr);
1345     msiobj_release(&mergerec->hdr);
1346
1347     return r;
1348 }
1349
1350 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1351                                       LPCWSTR table)
1352 {
1353     MSIRECORD *dbrec, *mergerec = NULL;
1354     UINT r, i, count;
1355
1356     r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1357     if (r != ERROR_SUCCESS)
1358         return r;
1359
1360     r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1361     if (r != ERROR_SUCCESS)
1362         goto done;
1363
1364     count = MSI_RecordGetFieldCount(dbrec);
1365     if (count != MSI_RecordGetFieldCount(mergerec))
1366     {
1367         r = ERROR_DATATYPE_MISMATCH;
1368         goto done;
1369     }
1370
1371     for (i = 1; i <= count; i++)
1372     {
1373         if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1374                      MSI_RecordGetString(mergerec, i)))
1375         {
1376             r = ERROR_DATATYPE_MISMATCH;
1377             goto done;
1378         }
1379     }
1380
1381 done:
1382     msiobj_release(&dbrec->hdr);
1383     msiobj_release(&mergerec->hdr);
1384
1385     return r;
1386 }
1387
1388 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1389 {
1390     MSIRECORD *colnames;
1391     LPWSTR str, val;
1392     UINT r, i = 0, sz = 0;
1393     int cmp;
1394
1395     r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1396     if (r != ERROR_SUCCESS)
1397         return NULL;
1398
1399     do
1400     {
1401         str = msi_dup_record_field(colnames, ++i);
1402         cmp = lstrcmpW(key, str);
1403         msi_free(str);
1404     } while (cmp);
1405
1406     msiobj_release(&colnames->hdr);
1407
1408     r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1409     if (r != ERROR_SUCCESS)
1410         return NULL;
1411     sz++;
1412
1413     if (MSI_RecordGetString(rec, i))  /* check record field is a string */
1414     {
1415         /* quote string record fields */
1416         const WCHAR szQuote[] = {'\'', 0};
1417         sz += 2;
1418         val = msi_alloc(sz*sizeof(WCHAR));
1419         if (!val)
1420             return NULL;
1421
1422         lstrcpyW(val, szQuote);
1423         r = MSI_RecordGetStringW(rec, i, val+1, &sz);
1424         lstrcpyW(val+1+sz, szQuote);
1425     }
1426     else
1427     {
1428         /* do not quote integer record fields */
1429         val = msi_alloc(sz*sizeof(WCHAR));
1430         if (!val)
1431             return NULL;
1432
1433         r = MSI_RecordGetStringW(rec, i, val, &sz);
1434     }
1435
1436     if (r != ERROR_SUCCESS)
1437     {
1438         ERR("failed to get string!\n");
1439         msi_free(val);
1440         return NULL;
1441     }
1442
1443     return val;
1444 }
1445
1446 static LPWSTR create_diff_row_query(MSIDATABASE *merge, MSIQUERY *view,
1447                                     LPWSTR table, MSIRECORD *rec)
1448 {
1449     LPWSTR query = NULL, clause = NULL;
1450     LPWSTR ptr = NULL, val;
1451     LPCWSTR setptr;
1452     DWORD size = 1, oldsize;
1453     LPCWSTR key;
1454     MSIRECORD *keys;
1455     UINT r, i, count;
1456
1457     static const WCHAR keyset[] = {
1458         '`','%','s','`',' ','=',' ','%','s',' ','A','N','D',' ',0};
1459     static const WCHAR lastkeyset[] = {
1460         '`','%','s','`',' ','=',' ','%','s',' ',0};
1461     static const WCHAR fmt[] = {'S','E','L','E','C','T',' ','*',' ',
1462         'F','R','O','M',' ','`','%','s','`',' ',
1463         'W','H','E','R','E',' ','%','s',0};
1464
1465     r = MSI_DatabaseGetPrimaryKeys(merge, table, &keys);
1466     if (r != ERROR_SUCCESS)
1467         return NULL;
1468
1469     clause = msi_alloc_zero(size * sizeof(WCHAR));
1470     if (!clause)
1471         goto done;
1472
1473     ptr = clause;
1474     count = MSI_RecordGetFieldCount(keys);
1475     for (i = 1; i <= count; i++)
1476     {
1477         key = MSI_RecordGetString(keys, i);
1478         val = get_key_value(view, key, rec);
1479
1480         if (i == count)
1481             setptr = lastkeyset;
1482         else
1483             setptr = keyset;
1484
1485         oldsize = size;
1486         size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1487         clause = msi_realloc(clause, size * sizeof (WCHAR));
1488         if (!clause)
1489         {
1490             msi_free(val);
1491             goto done;
1492         }
1493
1494         ptr = clause + oldsize - 1;
1495         sprintfW(ptr, setptr, key, val);
1496         msi_free(val);
1497     }
1498
1499     size = lstrlenW(fmt) + lstrlenW(table) + lstrlenW(clause) + 1;
1500     query = msi_alloc(size * sizeof(WCHAR));
1501     if (!query)
1502         goto done;
1503
1504     sprintfW(query, fmt, table, clause);
1505
1506 done:
1507     msi_free(clause);
1508     msiobj_release(&keys->hdr);
1509     return query;
1510 }
1511
1512 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1513 {
1514     MERGEDATA *data = param;
1515     MERGETABLE *table = data->curtable;
1516     MERGEROW *mergerow;
1517     MSIQUERY *dbview = NULL;
1518     MSIRECORD *row = NULL;
1519     LPWSTR query = NULL;
1520     UINT r = ERROR_SUCCESS;
1521
1522     if (TABLE_Exists(data->db, table->name))
1523     {
1524         query = create_diff_row_query(data->merge, data->curview, table->name, rec);
1525         if (!query)
1526             return ERROR_OUTOFMEMORY;
1527
1528         r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1529         if (r != ERROR_SUCCESS)
1530             goto done;
1531
1532         r = MSI_ViewExecute(dbview, NULL);
1533         if (r != ERROR_SUCCESS)
1534             goto done;
1535
1536         r = MSI_ViewFetch(dbview, &row);
1537         if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1538         {
1539             table->numconflicts++;
1540             goto done;
1541         }
1542         else if (r != ERROR_NO_MORE_ITEMS)
1543             goto done;
1544
1545         r = ERROR_SUCCESS;
1546     }
1547
1548     mergerow = msi_alloc(sizeof(MERGEROW));
1549     if (!mergerow)
1550     {
1551         r = ERROR_OUTOFMEMORY;
1552         goto done;
1553     }
1554
1555     mergerow->data = MSI_CloneRecord(rec);
1556     if (!mergerow->data)
1557     {
1558         r = ERROR_OUTOFMEMORY;
1559         msi_free(mergerow);
1560         goto done;
1561     }
1562
1563     list_add_tail(&table->rows, &mergerow->entry);
1564
1565 done:
1566     msi_free(query);
1567     msiobj_release(&row->hdr);
1568     msiobj_release(&dbview->hdr);
1569     return r;
1570 }
1571
1572 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1573 {
1574     UINT r, i, count;
1575     MSIRECORD *prec = NULL;
1576
1577     r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1578     if (r != ERROR_SUCCESS)
1579         return r;
1580
1581     count = MSI_RecordGetFieldCount(prec);
1582     *numlabels = count + 1;
1583     *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1584     if (!*labels)
1585     {
1586         r = ERROR_OUTOFMEMORY;
1587         goto end;
1588     }
1589
1590     (*labels)[0] = strdupW(table);
1591     for (i=1; i<=count; i++ )
1592     {
1593         (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1594     }
1595
1596 end:
1597     msiobj_release( &prec->hdr );
1598     return r;
1599 }
1600
1601 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1602 {
1603     UINT r, i, count;
1604     MSIRECORD *prec = NULL;
1605
1606     r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1607     if (r != ERROR_SUCCESS)
1608         return r;
1609
1610     count = MSI_RecordGetFieldCount(prec);
1611     *columns = msi_alloc(count*sizeof(LPWSTR));
1612     if (!*columns)
1613     {
1614         r = ERROR_OUTOFMEMORY;
1615         goto end;
1616     }
1617
1618     for (i=1; i<=count; i++ )
1619     {
1620         (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1621     }
1622
1623     *numcolumns = count;
1624
1625 end:
1626     msiobj_release( &prec->hdr );
1627     return r;
1628 }
1629
1630 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1631 {
1632     UINT r, i, count;
1633     MSIRECORD *prec = NULL;
1634
1635     r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1636     if (r != ERROR_SUCCESS)
1637         return r;
1638
1639     count = MSI_RecordGetFieldCount(prec);
1640     *types = msi_alloc(count*sizeof(LPWSTR));
1641     if (!*types)
1642     {
1643         r = ERROR_OUTOFMEMORY;
1644         goto end;
1645     }
1646
1647     *numtypes = count;
1648     for (i=1; i<=count; i++ )
1649     {
1650         (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1651     }
1652
1653 end:
1654     msiobj_release( &prec->hdr );
1655     return r;
1656 }
1657
1658 static void merge_free_rows(MERGETABLE *table)
1659 {
1660     struct list *item, *cursor;
1661
1662     LIST_FOR_EACH_SAFE(item, cursor, &table->rows)
1663     {
1664         MERGEROW *row = LIST_ENTRY(item, MERGEROW, entry);
1665
1666         list_remove(&row->entry);
1667         msiobj_release(&row->data->hdr);
1668         msi_free(row);
1669     }
1670 }
1671
1672 static void free_merge_table(MERGETABLE *table)
1673 {
1674     UINT i;
1675
1676     if (table->labels != NULL)
1677     {
1678         for (i = 0; i < table->numlabels; i++)
1679             msi_free(table->labels[i]);
1680
1681         msi_free(table->labels);
1682     }
1683
1684     if (table->columns != NULL)
1685     {
1686         for (i = 0; i < table->numcolumns; i++)
1687             msi_free(table->columns[i]);
1688
1689         msi_free(table->columns);
1690     }
1691
1692     if (table->types != NULL)
1693     {
1694         for (i = 0; i < table->numtypes; i++)
1695             msi_free(table->types[i]);
1696
1697         msi_free(table->types);
1698     }
1699
1700     msi_free(table->name);
1701     merge_free_rows(table);
1702
1703     msi_free(table);
1704 }
1705
1706 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1707 {
1708     UINT r;
1709     MERGETABLE *table;
1710     MSIQUERY *mergeview = NULL;
1711
1712     static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1713         'F','R','O','M',' ','`','%','s','`',0};
1714
1715     table = msi_alloc_zero(sizeof(MERGETABLE));
1716     if (!table)
1717     {
1718        *ptable = NULL;
1719        return ERROR_OUTOFMEMORY;
1720     }
1721
1722     r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1723     if (r != ERROR_SUCCESS)
1724         goto err;
1725
1726     r = MSI_OpenQuery(db, &mergeview, query, name);
1727     if (r != ERROR_SUCCESS)
1728         goto err;
1729
1730     r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1731     if (r != ERROR_SUCCESS)
1732         goto err;
1733
1734     r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1735     if (r != ERROR_SUCCESS)
1736         goto err;
1737
1738     list_init(&table->rows);
1739
1740     table->name = strdupW(name);
1741     table->numconflicts = 0;
1742
1743     msiobj_release(&mergeview->hdr);
1744     *ptable = table;
1745     return ERROR_SUCCESS;
1746
1747 err:
1748     msiobj_release(&mergeview->hdr);
1749     free_merge_table(table);
1750     *ptable = NULL;
1751     return r;
1752 }
1753
1754 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1755 {
1756     MERGEDATA *data = param;
1757     MERGETABLE *table;
1758     MSIQUERY *dbview = NULL;
1759     MSIQUERY *mergeview = NULL;
1760     LPCWSTR name;
1761     UINT r;
1762
1763     static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1764         'F','R','O','M',' ','`','%','s','`',0};
1765
1766     name = MSI_RecordGetString(rec, 1);
1767
1768     r = MSI_OpenQuery(data->merge, &mergeview, query, name);
1769     if (r != ERROR_SUCCESS)
1770         goto done;
1771
1772     if (TABLE_Exists(data->db, name))
1773     {
1774         r = MSI_OpenQuery(data->db, &dbview, query, name);
1775         if (r != ERROR_SUCCESS)
1776             goto done;
1777
1778         r = merge_verify_colnames(dbview, mergeview);
1779         if (r != ERROR_SUCCESS)
1780             goto done;
1781
1782         r = merge_verify_primary_keys(data->db, data->merge, name);
1783         if (r != ERROR_SUCCESS)
1784             goto done;
1785     }
1786
1787     r = msi_get_merge_table(data->merge, name, &table);
1788     if (r != ERROR_SUCCESS)
1789         goto done;
1790
1791     data->curtable = table;
1792     data->curview = mergeview;
1793     r = MSI_IterateRecords(mergeview, NULL, merge_diff_row, data);
1794     if (r != ERROR_SUCCESS)
1795     {
1796         free_merge_table(table);
1797         goto done;
1798     }
1799
1800     list_add_tail(data->tabledata, &table->entry);
1801
1802 done:
1803     msiobj_release(&dbview->hdr);
1804     msiobj_release(&mergeview->hdr);
1805     return r;
1806 }
1807
1808 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1809                               struct list *tabledata)
1810 {
1811     UINT r;
1812     MSIQUERY *view;
1813     MERGEDATA data;
1814
1815     static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1816         'F','R','O','M',' ','`','_','T','a','b','l','e','s','`',0};
1817
1818     r = MSI_DatabaseOpenViewW(merge, query, &view);
1819     if (r != ERROR_SUCCESS)
1820         return r;
1821
1822     data.db = db;
1823     data.merge = merge;
1824     data.tabledata = tabledata;
1825     r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1826
1827     msiobj_release(&view->hdr);
1828     return r;
1829 }
1830
1831 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1832 {
1833     UINT r;
1834     MERGEROW *row;
1835     MSIVIEW *tv;
1836
1837     if (!TABLE_Exists(db, table->name))
1838     {
1839         r = msi_add_table_to_db(db, table->columns, table->types,
1840                table->labels, table->numlabels, table->numcolumns);
1841         if (r != ERROR_SUCCESS)
1842            return ERROR_FUNCTION_FAILED;
1843     }
1844
1845     LIST_FOR_EACH_ENTRY(row, &table->rows, MERGEROW, entry)
1846     {
1847         r = TABLE_CreateView(db, table->name, &tv);
1848         if (r != ERROR_SUCCESS)
1849             return r;
1850
1851         r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1852         tv->ops->delete(tv);
1853
1854         if (r != ERROR_SUCCESS)
1855             return r;
1856     }
1857
1858     return ERROR_SUCCESS;
1859 }
1860
1861 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1862                                 LPWSTR table, DWORD numconflicts)
1863 {
1864     UINT r;
1865     MSIQUERY *view;
1866
1867     static const WCHAR create[] = {
1868         'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
1869         '`','%','s','`',' ','(','`','T','a','b','l','e','`',' ',
1870         'C','H','A','R','(','2','5','5',')',' ','N','O','T',' ',
1871         'N','U','L','L',',',' ','`','N','u','m','R','o','w','M','e','r','g','e',
1872         'C','o','n','f','l','i','c','t','s','`',' ','S','H','O','R','T',' ',
1873         'N','O','T',' ','N','U','L','L',' ','P','R','I','M','A','R','Y',' ',
1874         'K','E','Y',' ','`','T','a','b','l','e','`',')',0};
1875     static const WCHAR insert[] = {
1876         'I','N','S','E','R','T',' ','I','N','T','O',' ',
1877         '`','%','s','`',' ','(','`','T','a','b','l','e','`',',',' ',
1878         '`','N','u','m','R','o','w','M','e','r','g','e',
1879         'C','o','n','f','l','i','c','t','s','`',')',' ','V','A','L','U','E','S',
1880         ' ','(','\'','%','s','\'',',',' ','%','d',')',0};
1881
1882     if (!TABLE_Exists(db, error))
1883     {
1884         r = MSI_OpenQuery(db, &view, create, error);
1885         if (r != ERROR_SUCCESS)
1886             return r;
1887
1888         r = MSI_ViewExecute(view, NULL);
1889         msiobj_release(&view->hdr);
1890         if (r != ERROR_SUCCESS)
1891             return r;
1892     }
1893
1894     r = MSI_OpenQuery(db, &view, insert, error, table, numconflicts);
1895     if (r != ERROR_SUCCESS)
1896         return r;
1897
1898     r = MSI_ViewExecute(view, NULL);
1899     msiobj_release(&view->hdr);
1900     return r;
1901 }
1902
1903 UINT WINAPI MsiDatabaseMergeW(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1904                               LPCWSTR szTableName)
1905 {
1906     struct list tabledata = LIST_INIT(tabledata);
1907     struct list *item, *cursor;
1908     MSIDATABASE *db, *merge;
1909     MERGETABLE *table;
1910     BOOL conflicts;
1911     UINT r;
1912
1913     TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1914           debugstr_w(szTableName));
1915
1916     if (szTableName && !*szTableName)
1917         return ERROR_INVALID_TABLE;
1918
1919     db = msihandle2msiinfo(hDatabase, MSIHANDLETYPE_DATABASE);
1920     merge = msihandle2msiinfo(hDatabaseMerge, MSIHANDLETYPE_DATABASE);
1921     if (!db || !merge)
1922     {
1923         r = ERROR_INVALID_HANDLE;
1924         goto done;
1925     }
1926
1927     r = gather_merge_data(db, merge, &tabledata);
1928     if (r != ERROR_SUCCESS)
1929         goto done;
1930
1931     conflicts = FALSE;
1932     LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
1933     {
1934         if (table->numconflicts)
1935         {
1936             conflicts = TRUE;
1937
1938             r = update_merge_errors(db, szTableName, table->name,
1939                                     table->numconflicts);
1940             if (r != ERROR_SUCCESS)
1941                 break;
1942         }
1943         else
1944         {
1945             r = merge_table(db, table);
1946             if (r != ERROR_SUCCESS)
1947                 break;
1948         }
1949     }
1950
1951     LIST_FOR_EACH_SAFE(item, cursor, &tabledata)
1952     {
1953         MERGETABLE *table = LIST_ENTRY(item, MERGETABLE, entry);
1954         list_remove(&table->entry);
1955         free_merge_table(table);
1956     }
1957
1958     if (conflicts)
1959         r = ERROR_FUNCTION_FAILED;
1960
1961 done:
1962     msiobj_release(&db->hdr);
1963     msiobj_release(&merge->hdr);
1964     return r;
1965 }
1966
1967 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
1968 {
1969     MSIDBSTATE ret = MSIDBSTATE_READ;
1970     MSIDATABASE *db;
1971
1972     TRACE("%d\n", handle);
1973
1974     db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1975     if( !db )
1976     {
1977         IWineMsiRemoteDatabase *remote_database;
1978
1979         remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1980         if ( !remote_database )
1981             return MSIDBSTATE_ERROR;
1982
1983         IWineMsiRemoteDatabase_Release( remote_database );
1984         WARN("MsiGetDatabaseState not allowed during a custom action!\n");
1985
1986         return MSIDBSTATE_READ;
1987     }
1988
1989     if (db->mode != MSIDBOPEN_READONLY )
1990         ret = MSIDBSTATE_WRITE;
1991     msiobj_release( &db->hdr );
1992
1993     return ret;
1994 }
1995
1996 typedef struct _msi_remote_database_impl {
1997     const IWineMsiRemoteDatabaseVtbl *lpVtbl;
1998     MSIHANDLE database;
1999     LONG refs;
2000 } msi_remote_database_impl;
2001
2002 static inline msi_remote_database_impl* mrd_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase* iface )
2003 {
2004     return (msi_remote_database_impl *)iface;
2005 }
2006
2007 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
2008                                           REFIID riid,LPVOID *ppobj)
2009 {
2010     if( IsEqualCLSID( riid, &IID_IUnknown ) ||
2011         IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
2012     {
2013         IUnknown_AddRef( iface );
2014         *ppobj = iface;
2015         return S_OK;
2016     }
2017
2018     return E_NOINTERFACE;
2019 }
2020
2021 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
2022 {
2023     msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
2024
2025     return InterlockedIncrement( &This->refs );
2026 }
2027
2028 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
2029 {
2030     msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
2031     ULONG r;
2032
2033     r = InterlockedDecrement( &This->refs );
2034     if (r == 0)
2035     {
2036         MsiCloseHandle( This->database );
2037         msi_free( This );
2038     }
2039     return r;
2040 }
2041
2042 static HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
2043                                              LPCWSTR table, MSICONDITION *persistent )
2044 {
2045     msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2046     *persistent = MsiDatabaseIsTablePersistentW(This->database, table);
2047     return S_OK;
2048 }
2049
2050 static HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
2051                                           LPCWSTR table, MSIHANDLE *keys )
2052 {
2053     msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2054     UINT r = MsiDatabaseGetPrimaryKeysW(This->database, table, keys);
2055     return HRESULT_FROM_WIN32(r);
2056 }
2057
2058 static HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
2059                                                 UINT updatecount, MSIHANDLE *suminfo )
2060 {
2061     msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2062     UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
2063     return HRESULT_FROM_WIN32(r);
2064 }
2065
2066 static HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
2067                                     LPCWSTR query, MSIHANDLE *view )
2068 {
2069     msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2070     UINT r = MsiDatabaseOpenViewW(This->database, query, view);
2071     return HRESULT_FROM_WIN32(r);
2072 }
2073
2074 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
2075 {
2076     msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
2077     This->database = handle;
2078     return S_OK;
2079 }
2080
2081 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
2082 {
2083     mrd_QueryInterface,
2084     mrd_AddRef,
2085     mrd_Release,
2086     mrd_IsTablePersistent,
2087     mrd_GetPrimaryKeys,
2088     mrd_GetSummaryInformation,
2089     mrd_OpenView,
2090     mrd_SetMsiHandle,
2091 };
2092
2093 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
2094 {
2095     msi_remote_database_impl *This;
2096
2097     This = msi_alloc( sizeof *This );
2098     if (!This)
2099         return E_OUTOFMEMORY;
2100
2101     This->lpVtbl = &msi_remote_database_vtbl;
2102     This->database = 0;
2103     This->refs = 1;
2104
2105     *ppObj = This;
2106
2107     return S_OK;
2108 }