msi/tests: Move test coverage for standard actions to a separate module.
[wine.git] / dlls / msi / database.c
blob3007d485b2b5650b06e962f4725750886aada400
1 /*
2 * Implementation of the Microsoft Installer (msi.dll)
4 * Copyright 2002,2003,2004,2005 Mike McCormack for CodeWeavers
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.
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.
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
21 #include <stdarg.h>
23 #define COBJMACROS
24 #define NONAMELESSUNION
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"
40 #include "initguid.h"
42 WINE_DEFAULT_DEBUG_CHANNEL(msi);
45 * .MSI file format
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.
54 #define IS_INTMSIDBOPEN(x) (((ULONG_PTR)(x) >> 16) == 0)
56 typedef struct tagMSITRANSFORM {
57 struct list entry;
58 IStorage *stg;
59 } MSITRANSFORM;
61 typedef struct tagMSISTREAM {
62 struct list entry;
63 IStream *stm;
64 } MSISTREAM;
66 static UINT find_open_stream( MSIDATABASE *db, LPCWSTR name, IStream **stm )
68 MSISTREAM *stream;
70 LIST_FOR_EACH_ENTRY( stream, &db->streams, MSISTREAM, entry )
72 HRESULT r;
73 STATSTG stat;
75 r = IStream_Stat( stream->stm, &stat, 0 );
76 if( FAILED( r ) )
78 WARN("failed to stat stream r = %08x!\n", r);
79 continue;
82 if( !lstrcmpW( name, stat.pwcsName ) )
84 TRACE("found %s\n", debugstr_w(name));
85 *stm = stream->stm;
86 CoTaskMemFree( stat.pwcsName );
87 return ERROR_SUCCESS;
90 CoTaskMemFree( stat.pwcsName );
93 return ERROR_FUNCTION_FAILED;
96 static UINT clone_open_stream( MSIDATABASE *db, LPCWSTR name, IStream **stm )
98 IStream *stream;
100 if (find_open_stream( db, name, &stream ) == ERROR_SUCCESS)
102 HRESULT r;
103 LARGE_INTEGER pos;
105 r = IStream_Clone( stream, stm );
106 if( FAILED( r ) )
108 WARN("failed to clone stream r = %08x!\n", r);
109 return ERROR_FUNCTION_FAILED;
112 pos.QuadPart = 0;
113 r = IStream_Seek( *stm, pos, STREAM_SEEK_SET, NULL );
114 if( FAILED( r ) )
116 IStream_Release( *stm );
117 return ERROR_FUNCTION_FAILED;
120 return ERROR_SUCCESS;
123 return ERROR_FUNCTION_FAILED;
126 UINT db_get_raw_stream( MSIDATABASE *db, LPCWSTR stname, IStream **stm )
128 HRESULT r;
129 WCHAR decoded[MAX_STREAM_NAME_LEN];
131 decode_streamname( stname, decoded );
132 TRACE("%s -> %s\n", debugstr_w(stname), debugstr_w(decoded));
134 if (clone_open_stream( db, stname, stm ) == ERROR_SUCCESS)
135 return ERROR_SUCCESS;
137 r = IStorage_OpenStream( db->storage, stname, NULL,
138 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
139 if( FAILED( r ) )
141 MSITRANSFORM *transform;
143 LIST_FOR_EACH_ENTRY( transform, &db->transforms, MSITRANSFORM, entry )
145 r = IStorage_OpenStream( transform->stg, stname, NULL,
146 STGM_READ | STGM_SHARE_EXCLUSIVE, 0, stm );
147 if (SUCCEEDED(r))
148 break;
152 if( SUCCEEDED(r) )
154 MSISTREAM *stream;
156 stream = msi_alloc( sizeof(MSISTREAM) );
157 if( !stream )
158 return ERROR_NOT_ENOUGH_MEMORY;
160 stream->stm = *stm;
161 IStream_AddRef( *stm );
162 list_add_tail( &db->streams, &stream->entry );
165 return SUCCEEDED(r) ? ERROR_SUCCESS : ERROR_FUNCTION_FAILED;
168 static void free_transforms( MSIDATABASE *db )
170 while( !list_empty( &db->transforms ) )
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 );
180 void db_destroy_stream( MSIDATABASE *db, LPCWSTR stname )
182 MSISTREAM *stream, *stream2;
184 LIST_FOR_EACH_ENTRY_SAFE( stream, stream2, &db->streams, MSISTREAM, entry )
186 HRESULT r;
187 STATSTG stat;
189 r = IStream_Stat( stream->stm, &stat, 0 );
190 if (FAILED(r))
192 WARN("failed to stat stream r = %08x\n", r);
193 continue;
196 if (!strcmpW( stname, stat.pwcsName ))
198 TRACE("destroying %s\n", debugstr_w(stname));
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;
207 CoTaskMemFree( stat.pwcsName );
211 static void free_streams( MSIDATABASE *db )
213 while( !list_empty( &db->streams ) )
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 );
223 void append_storage_to_db( MSIDATABASE *db, IStorage *stg )
225 MSITRANSFORM *t;
227 t = msi_alloc( sizeof *t );
228 t->stg = stg;
229 IStorage_AddRef( stg );
230 list_add_head( &db->transforms, &t->entry );
232 /* the transform may add or replace streams */
233 free_streams( db );
236 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
238 MSIDATABASE *db = (MSIDATABASE *) arg;
240 msi_free(db->path);
241 free_cached_tables( db );
242 free_streams( db );
243 free_transforms( db );
244 if (db->strings) msi_destroy_stringtable( db->strings );
245 IStorage_Release( db->storage );
246 if (db->deletefile)
248 DeleteFileW( db->deletefile );
249 msi_free( db->deletefile );
251 if (db->localfile)
253 DeleteFileW( db->localfile );
254 msi_free( db->localfile );
258 static HRESULT db_initialize( IStorage *stg, const GUID *clsid )
260 static const WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
261 HRESULT hr;
263 hr = IStorage_SetClass( stg, clsid );
264 if (FAILED( hr ))
266 WARN("failed to set class id 0x%08x\n", hr);
267 return hr;
270 /* create the _Tables stream */
271 hr = write_stream_data( stg, szTables, NULL, 0, TRUE );
272 if (FAILED( hr ))
274 WARN("failed to create _Tables stream 0x%08x\n", hr);
275 return hr;
278 hr = msi_init_string_table( stg );
279 if (FAILED( hr ))
281 WARN("failed to initialize string table 0x%08x\n", hr);
282 return hr;
285 hr = IStorage_Commit( stg, 0 );
286 if (FAILED( hr ))
288 WARN("failed to commit changes 0x%08x\n", hr);
289 return hr;
292 return S_OK;
295 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
297 IStorage *stg = NULL;
298 HRESULT r;
299 MSIDATABASE *db = NULL;
300 UINT ret = ERROR_FUNCTION_FAILED;
301 LPCWSTR szMode, save_path;
302 STATSTG stat;
303 BOOL created = FALSE, patch = FALSE;
304 WCHAR path[MAX_PATH];
306 TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
308 if( !pdb )
309 return ERROR_INVALID_PARAMETER;
311 if (szPersist - MSIDBOPEN_PATCHFILE >= MSIDBOPEN_READONLY &&
312 szPersist - MSIDBOPEN_PATCHFILE <= MSIDBOPEN_CREATEDIRECT)
314 TRACE("Database is a patch\n");
315 szPersist -= MSIDBOPEN_PATCHFILE;
316 patch = TRUE;
319 save_path = szDBPath;
320 szMode = szPersist;
321 if( !IS_INTMSIDBOPEN(szPersist) )
323 if (!CopyFileW( szDBPath, szPersist, FALSE ))
324 return ERROR_OPEN_FAILED;
326 szDBPath = szPersist;
327 szPersist = MSIDBOPEN_TRANSACT;
328 created = TRUE;
331 if( szPersist == MSIDBOPEN_READONLY )
333 r = StgOpenStorage( szDBPath, NULL,
334 STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
336 else if( szPersist == MSIDBOPEN_CREATE )
338 r = StgCreateDocfile( szDBPath,
339 STGM_CREATE|STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
341 if( SUCCEEDED(r) )
342 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
343 created = TRUE;
345 else if( szPersist == MSIDBOPEN_CREATEDIRECT )
347 r = StgCreateDocfile( szDBPath,
348 STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg );
350 if( SUCCEEDED(r) )
351 r = db_initialize( stg, patch ? &CLSID_MsiPatch : &CLSID_MsiDatabase );
352 created = TRUE;
354 else if( szPersist == MSIDBOPEN_TRANSACT )
356 r = StgOpenStorage( szDBPath, NULL,
357 STGM_TRANSACTED|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
359 else if( szPersist == MSIDBOPEN_DIRECT )
361 r = StgOpenStorage( szDBPath, NULL,
362 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
364 else
366 ERR("unknown flag %p\n",szPersist);
367 return ERROR_INVALID_PARAMETER;
370 if( FAILED( r ) || !stg )
372 FIXME("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
373 return ERROR_FUNCTION_FAILED;
376 r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
377 if( FAILED( r ) )
379 FIXME("Failed to stat storage\n");
380 goto end;
383 if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
384 !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) &&
385 !IsEqualGUID( &stat.clsid, &CLSID_MsiTransform ) )
387 ERR("storage GUID is not a MSI database GUID %s\n",
388 debugstr_guid(&stat.clsid) );
389 goto end;
392 if ( patch && !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) )
394 ERR("storage GUID is not the MSI patch GUID %s\n",
395 debugstr_guid(&stat.clsid) );
396 ret = ERROR_OPEN_FAILED;
397 goto end;
400 db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
401 MSI_CloseDatabase );
402 if( !db )
404 FIXME("Failed to allocate a handle\n");
405 goto end;
408 if (!strchrW( save_path, '\\' ))
410 GetCurrentDirectoryW( MAX_PATH, path );
411 lstrcatW( path, szBackSlash );
412 lstrcatW( path, save_path );
414 else
415 lstrcpyW( path, save_path );
417 db->path = strdupW( path );
419 if( TRACE_ON( msi ) )
420 enum_stream_names( stg );
422 db->storage = stg;
423 db->mode = szMode;
424 if (created)
425 db->deletefile = strdupW( szDBPath );
426 list_init( &db->tables );
427 list_init( &db->transforms );
428 list_init( &db->streams );
430 db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
431 if( !db->strings )
432 goto end;
434 ret = ERROR_SUCCESS;
436 msiobj_addref( &db->hdr );
437 IStorage_AddRef( stg );
438 *pdb = db;
440 end:
441 if( db )
442 msiobj_release( &db->hdr );
443 if( stg )
444 IStorage_Release( stg );
446 return ret;
449 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
451 MSIDATABASE *db;
452 UINT ret;
454 TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
456 ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
457 if( ret == ERROR_SUCCESS )
459 *phDB = alloc_msihandle( &db->hdr );
460 if (! *phDB)
461 ret = ERROR_NOT_ENOUGH_MEMORY;
462 msiobj_release( &db->hdr );
465 return ret;
468 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
470 HRESULT r = ERROR_FUNCTION_FAILED;
471 LPWSTR szwDBPath = NULL, szwPersist = NULL;
473 TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
475 if( szDBPath )
477 szwDBPath = strdupAtoW( szDBPath );
478 if( !szwDBPath )
479 goto end;
482 if( !IS_INTMSIDBOPEN(szPersist) )
484 szwPersist = strdupAtoW( szPersist );
485 if( !szwPersist )
486 goto end;
488 else
489 szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
491 r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
493 end:
494 if( !IS_INTMSIDBOPEN(szPersist) )
495 msi_free( szwPersist );
496 msi_free( szwDBPath );
498 return r;
501 static LPWSTR msi_read_text_archive(LPCWSTR path)
503 HANDLE file;
504 LPSTR data = NULL;
505 LPWSTR wdata = NULL;
506 DWORD read, size = 0;
508 file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
509 if (file == INVALID_HANDLE_VALUE)
510 return NULL;
512 size = GetFileSize( file, NULL );
513 data = msi_alloc( size + 1 );
514 if (!data)
515 goto done;
517 if (!ReadFile( file, data, size, &read, NULL ))
518 goto done;
520 data[size] = '\0';
521 wdata = strdupAtoW( data );
523 done:
524 CloseHandle( file );
525 msi_free( data );
526 return wdata;
529 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries)
531 LPWSTR ptr = *line, save;
532 DWORD i, count = 1;
534 *entries = NULL;
536 /* stay on this line */
537 while (*ptr && *ptr != '\n')
539 /* entries are separated by tabs */
540 if (*ptr == '\t')
541 count++;
543 ptr++;
546 *entries = msi_alloc(count * sizeof(LPWSTR));
547 if (!*entries)
548 return;
550 /* store pointers into the data */
551 for (i = 0, ptr = *line; i < count; i++)
553 while (*ptr && *ptr == '\r') ptr++;
554 save = ptr;
556 while (*ptr && *ptr != '\t' && *ptr != '\n' && *ptr != '\r') ptr++;
558 /* NULL-separate the data */
559 if (*ptr == '\n' || *ptr == '\r')
561 while (*ptr == '\n' || *ptr == '\r')
562 *(ptr++) = '\0';
564 else if (*ptr)
565 *ptr++ = '\0';
567 (*entries)[i] = save;
570 /* move to the next line if there's more, else EOF */
571 *line = ptr;
573 if (num_entries)
574 *num_entries = count;
577 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
579 LPWSTR prelude;
580 DWORD size;
582 static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
584 size = sizeof(create_fmt)/sizeof(create_fmt[0]) + lstrlenW(table) - 2;
585 prelude = msi_alloc(size * sizeof(WCHAR));
586 if (!prelude)
587 return NULL;
589 sprintfW(prelude, create_fmt, table);
590 return prelude;
593 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
595 LPWSTR columns, p;
596 LPCWSTR type;
597 DWORD sql_size = 1, i, len;
598 WCHAR expanded[128], *ptr;
599 WCHAR size[10], comma[2], extra[30];
601 static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
602 static const WCHAR size_fmt[] = {'(','%','s',')',0};
603 static const WCHAR type_char[] = {'C','H','A','R',0};
604 static const WCHAR type_int[] = {'I','N','T',0};
605 static const WCHAR type_long[] = {'L','O','N','G',0};
606 static const WCHAR type_object[] = {'O','B','J','E','C','T',0};
607 static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
608 static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
610 columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
611 if (!columns)
612 return NULL;
614 for (i = 0; i < num_columns; i++)
616 type = NULL;
617 comma[1] = size[0] = extra[0] = '\0';
619 if (i == num_columns - 1)
620 comma[0] = '\0';
621 else
622 comma[0] = ',';
624 ptr = &types[i][1];
625 len = atolW(ptr);
626 extra[0] = '\0';
628 switch (types[i][0])
630 case 'l':
631 lstrcpyW(extra, type_notnull);
632 case 'L':
633 lstrcatW(extra, localizable);
634 type = type_char;
635 sprintfW(size, size_fmt, ptr);
636 break;
637 case 's':
638 lstrcpyW(extra, type_notnull);
639 case 'S':
640 type = type_char;
641 sprintfW(size, size_fmt, ptr);
642 break;
643 case 'i':
644 lstrcpyW(extra, type_notnull);
645 case 'I':
646 if (len <= 2)
647 type = type_int;
648 else if (len == 4)
649 type = type_long;
650 else
652 WARN("invalid int width %u\n", len);
653 msi_free(columns);
654 return NULL;
656 break;
657 case 'v':
658 lstrcpyW(extra, type_notnull);
659 case 'V':
660 type = type_object;
661 break;
662 default:
663 ERR("Unknown type: %c\n", types[i][0]);
664 msi_free(columns);
665 return NULL;
668 sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
669 sql_size += lstrlenW(expanded);
671 p = msi_realloc(columns, sql_size * sizeof(WCHAR));
672 if (!p)
674 msi_free(columns);
675 return NULL;
677 columns = p;
679 lstrcatW(columns, expanded);
682 return columns;
685 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
687 LPWSTR postlude, keys, ptr;
688 DWORD size, key_size, i;
690 static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
691 static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
693 for (i = 0, size = 1; i < num_keys; i++)
694 size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
696 keys = msi_alloc(size * sizeof(WCHAR));
697 if (!keys)
698 return NULL;
700 for (i = 0, ptr = keys; i < num_keys; i++)
702 key_size = lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) -2;
703 sprintfW(ptr, key_fmt, primary_keys[i]);
704 ptr += key_size;
707 /* remove final ', ' */
708 *(ptr - 2) = '\0';
710 size = lstrlenW(postlude_fmt) + size - 1;
711 postlude = msi_alloc(size * sizeof(WCHAR));
712 if (!postlude)
713 goto done;
715 sprintfW(postlude, postlude_fmt, keys);
717 done:
718 msi_free(keys);
719 return postlude;
722 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
724 UINT r = ERROR_OUTOFMEMORY;
725 DWORD size;
726 MSIQUERY *view;
727 LPWSTR create_sql = NULL;
728 LPWSTR prelude, columns_sql, postlude;
730 prelude = msi_build_createsql_prelude(labels[0]);
731 columns_sql = msi_build_createsql_columns(columns, types, num_columns);
732 postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
734 if (!prelude || !columns_sql || !postlude)
735 goto done;
737 size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
738 create_sql = msi_alloc(size * sizeof(WCHAR));
739 if (!create_sql)
740 goto done;
742 lstrcpyW(create_sql, prelude);
743 lstrcatW(create_sql, columns_sql);
744 lstrcatW(create_sql, postlude);
746 r = MSI_DatabaseOpenViewW( db, create_sql, &view );
747 if (r != ERROR_SUCCESS)
748 goto done;
750 r = MSI_ViewExecute(view, NULL);
751 MSI_ViewClose(view);
752 msiobj_release(&view->hdr);
754 done:
755 msi_free(prelude);
756 msi_free(columns_sql);
757 msi_free(postlude);
758 msi_free(create_sql);
759 return r;
762 static LPWSTR msi_import_stream_filename(LPCWSTR path, LPCWSTR name)
764 DWORD len;
765 LPWSTR fullname, ptr;
767 len = lstrlenW(path) + lstrlenW(name) + 1;
768 fullname = msi_alloc(len*sizeof(WCHAR));
769 if (!fullname)
770 return NULL;
772 lstrcpyW( fullname, path );
774 /* chop off extension from path */
775 ptr = strrchrW(fullname, '.');
776 if (!ptr)
778 msi_free (fullname);
779 return NULL;
781 *ptr++ = '\\';
782 lstrcpyW( ptr, name );
783 return fullname;
786 static UINT construct_record(DWORD num_columns, LPWSTR *types,
787 LPWSTR *data, LPWSTR path, MSIRECORD **rec)
789 UINT i;
791 *rec = MSI_CreateRecord(num_columns);
792 if (!*rec)
793 return ERROR_OUTOFMEMORY;
795 for (i = 0; i < num_columns; i++)
797 switch (types[i][0])
799 case 'L': case 'l': case 'S': case 's':
800 MSI_RecordSetStringW(*rec, i + 1, data[i]);
801 break;
802 case 'I': case 'i':
803 if (*data[i])
804 MSI_RecordSetInteger(*rec, i + 1, atoiW(data[i]));
805 break;
806 case 'V': case 'v':
807 if (*data[i])
809 UINT r;
810 LPWSTR file = msi_import_stream_filename(path, data[i]);
811 if (!file)
812 return ERROR_FUNCTION_FAILED;
814 r = MSI_RecordSetStreamFromFileW(*rec, i + 1, file);
815 msi_free (file);
816 if (r != ERROR_SUCCESS)
817 return ERROR_FUNCTION_FAILED;
819 break;
820 default:
821 ERR("Unhandled column type: %c\n", types[i][0]);
822 msiobj_release(&(*rec)->hdr);
823 return ERROR_FUNCTION_FAILED;
827 return ERROR_SUCCESS;
830 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
831 LPWSTR *labels, LPWSTR **records,
832 int num_columns, int num_records,
833 LPWSTR path)
835 UINT r;
836 int i;
837 MSIQUERY *view;
838 MSIRECORD *rec;
840 static const WCHAR select[] = {
841 'S','E','L','E','C','T',' ','*',' ',
842 'F','R','O','M',' ','`','%','s','`',0
845 r = MSI_OpenQuery(db, &view, select, labels[0]);
846 if (r != ERROR_SUCCESS)
847 return r;
849 while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
851 r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
852 msiobj_release(&rec->hdr);
853 if (r != ERROR_SUCCESS)
854 goto done;
857 for (i = 0; i < num_records; i++)
859 r = construct_record(num_columns, types, records[i], path, &rec);
860 if (r != ERROR_SUCCESS)
861 goto done;
863 r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
864 if (r != ERROR_SUCCESS)
866 msiobj_release(&rec->hdr);
867 goto done;
870 msiobj_release(&rec->hdr);
873 done:
874 msiobj_release(&view->hdr);
875 return r;
878 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
880 UINT r;
881 DWORD len, i;
882 DWORD num_labels, num_types;
883 DWORD num_columns, num_records = 0;
884 LPWSTR *columns, *types, *labels;
885 LPWSTR path, ptr, data;
886 LPWSTR **records = NULL;
887 LPWSTR **temp_records;
889 static const WCHAR suminfo[] =
890 {'_','S','u','m','m','a','r','y','I','n','f','o','r','m','a','t','i','o','n',0};
892 TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
894 if( folder == NULL || file == NULL )
895 return ERROR_INVALID_PARAMETER;
897 len = lstrlenW(folder) + lstrlenW(szBackSlash) + lstrlenW(file) + 1;
898 path = msi_alloc( len * sizeof(WCHAR) );
899 if (!path)
900 return ERROR_OUTOFMEMORY;
902 lstrcpyW( path, folder );
903 lstrcatW( path, szBackSlash );
904 lstrcatW( path, file );
906 data = msi_read_text_archive( path );
908 ptr = data;
909 msi_parse_line( &ptr, &columns, &num_columns );
910 msi_parse_line( &ptr, &types, &num_types );
911 msi_parse_line( &ptr, &labels, &num_labels );
913 if (num_columns != num_types)
915 r = ERROR_FUNCTION_FAILED;
916 goto done;
919 records = msi_alloc(sizeof(LPWSTR *));
920 if (!records)
922 r = ERROR_OUTOFMEMORY;
923 goto done;
926 /* read in the table records */
927 while (*ptr)
929 msi_parse_line( &ptr, &records[num_records], NULL );
931 num_records++;
932 temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
933 if (!temp_records)
935 r = ERROR_OUTOFMEMORY;
936 goto done;
938 records = temp_records;
941 if (!strcmpW(labels[0], suminfo))
943 r = msi_add_suminfo( db, records, num_records, num_columns );
944 if (r != ERROR_SUCCESS)
946 r = ERROR_FUNCTION_FAILED;
947 goto done;
950 else
952 if (!TABLE_Exists(db, labels[0]))
954 r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
955 if (r != ERROR_SUCCESS)
957 r = ERROR_FUNCTION_FAILED;
958 goto done;
962 r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records, path );
965 done:
966 msi_free(path);
967 msi_free(data);
968 msi_free(columns);
969 msi_free(types);
970 msi_free(labels);
972 for (i = 0; i < num_records; i++)
973 msi_free(records[i]);
975 msi_free(records);
977 return r;
980 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
982 MSIDATABASE *db;
983 UINT r;
985 TRACE("%x %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
987 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
988 if( !db )
990 IWineMsiRemoteDatabase *remote_database;
992 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
993 if ( !remote_database )
994 return ERROR_INVALID_HANDLE;
996 IWineMsiRemoteDatabase_Release( remote_database );
997 WARN("MsiDatabaseImport not allowed during a custom action!\n");
999 return ERROR_SUCCESS;
1002 r = MSI_DatabaseImport( db, szFolder, szFilename );
1003 msiobj_release( &db->hdr );
1004 return r;
1007 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
1008 LPCSTR szFolder, LPCSTR szFilename )
1010 LPWSTR path = NULL, file = NULL;
1011 UINT r = ERROR_OUTOFMEMORY;
1013 TRACE("%x %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
1015 if( szFolder )
1017 path = strdupAtoW( szFolder );
1018 if( !path )
1019 goto end;
1022 if( szFilename )
1024 file = strdupAtoW( szFilename );
1025 if( !file )
1026 goto end;
1029 r = MsiDatabaseImportW( handle, path, file );
1031 end:
1032 msi_free( path );
1033 msi_free( file );
1035 return r;
1038 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
1040 UINT i, count, len, r = ERROR_SUCCESS;
1041 const char *sep;
1042 char *buffer;
1043 DWORD sz;
1045 len = 0x100;
1046 buffer = msi_alloc( len );
1047 if ( !buffer )
1048 return ERROR_OUTOFMEMORY;
1050 count = MSI_RecordGetFieldCount( row );
1051 for ( i=start; i<=count; i++ )
1053 sz = len;
1054 r = MSI_RecordGetStringA( row, i, buffer, &sz );
1055 if (r == ERROR_MORE_DATA)
1057 char *p = msi_realloc( buffer, sz + 1 );
1058 if (!p)
1059 break;
1060 len = sz + 1;
1061 buffer = p;
1063 sz = len;
1064 r = MSI_RecordGetStringA( row, i, buffer, &sz );
1065 if (r != ERROR_SUCCESS)
1066 break;
1068 if (!WriteFile( handle, buffer, sz, &sz, NULL ))
1070 r = ERROR_FUNCTION_FAILED;
1071 break;
1074 sep = (i < count) ? "\t" : "\r\n";
1075 if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
1077 r = ERROR_FUNCTION_FAILED;
1078 break;
1081 msi_free( buffer );
1082 return r;
1085 static UINT msi_export_row( MSIRECORD *row, void *arg )
1087 return msi_export_record( arg, row, 1 );
1090 static UINT msi_export_forcecodepage( HANDLE handle )
1092 DWORD sz;
1094 static const char data[] = "\r\n\r\n0\t_ForceCodepage\r\n";
1096 FIXME("Read the codepage from the strings table!\n");
1098 sz = lstrlenA(data) + 1;
1099 if (!WriteFile(handle, data, sz, &sz, NULL))
1100 return ERROR_FUNCTION_FAILED;
1102 return ERROR_SUCCESS;
1105 static UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
1106 LPCWSTR folder, LPCWSTR file )
1108 static const WCHAR query[] = {
1109 's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
1110 static const WCHAR forcecodepage[] = {
1111 '_','F','o','r','c','e','C','o','d','e','p','a','g','e',0 };
1112 MSIRECORD *rec = NULL;
1113 MSIQUERY *view = NULL;
1114 LPWSTR filename;
1115 HANDLE handle;
1116 UINT len, r;
1118 TRACE("%p %s %s %s\n", db, debugstr_w(table),
1119 debugstr_w(folder), debugstr_w(file) );
1121 if( folder == NULL || file == NULL )
1122 return ERROR_INVALID_PARAMETER;
1124 len = lstrlenW(folder) + lstrlenW(file) + 2;
1125 filename = msi_alloc(len * sizeof (WCHAR));
1126 if (!filename)
1127 return ERROR_OUTOFMEMORY;
1129 lstrcpyW( filename, folder );
1130 lstrcatW( filename, szBackSlash );
1131 lstrcatW( filename, file );
1133 handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
1134 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
1135 msi_free( filename );
1136 if (handle == INVALID_HANDLE_VALUE)
1137 return ERROR_FUNCTION_FAILED;
1139 if (!lstrcmpW( table, forcecodepage ))
1141 r = msi_export_forcecodepage( handle );
1142 goto done;
1145 r = MSI_OpenQuery( db, &view, query, table );
1146 if (r == ERROR_SUCCESS)
1148 /* write out row 1, the column names */
1149 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
1150 if (r == ERROR_SUCCESS)
1152 msi_export_record( handle, rec, 1 );
1153 msiobj_release( &rec->hdr );
1156 /* write out row 2, the column types */
1157 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
1158 if (r == ERROR_SUCCESS)
1160 msi_export_record( handle, rec, 1 );
1161 msiobj_release( &rec->hdr );
1164 /* write out row 3, the table name + keys */
1165 r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
1166 if (r == ERROR_SUCCESS)
1168 MSI_RecordSetStringW( rec, 0, table );
1169 msi_export_record( handle, rec, 0 );
1170 msiobj_release( &rec->hdr );
1173 /* write out row 4 onwards, the data */
1174 r = MSI_IterateRecords( view, 0, msi_export_row, handle );
1175 msiobj_release( &view->hdr );
1178 done:
1179 CloseHandle( handle );
1180 return r;
1183 /***********************************************************************
1184 * MsiExportDatabaseW [MSI.@]
1186 * Writes a file containing the table data as tab separated ASCII.
1188 * The format is as follows:
1190 * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
1191 * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
1192 * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
1194 * Followed by the data, starting at row 1 with one row per line
1196 * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
1198 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
1199 LPCWSTR szFolder, LPCWSTR szFilename )
1201 MSIDATABASE *db;
1202 UINT r;
1204 TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
1205 debugstr_w(szFolder), debugstr_w(szFilename));
1207 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1208 if( !db )
1210 IWineMsiRemoteDatabase *remote_database;
1212 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1213 if ( !remote_database )
1214 return ERROR_INVALID_HANDLE;
1216 IWineMsiRemoteDatabase_Release( remote_database );
1217 WARN("MsiDatabaseExport not allowed during a custom action!\n");
1219 return ERROR_SUCCESS;
1222 r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
1223 msiobj_release( &db->hdr );
1224 return r;
1227 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
1228 LPCSTR szFolder, LPCSTR szFilename )
1230 LPWSTR path = NULL, file = NULL, table = NULL;
1231 UINT r = ERROR_OUTOFMEMORY;
1233 TRACE("%x %s %s %s\n", handle, debugstr_a(szTable),
1234 debugstr_a(szFolder), debugstr_a(szFilename));
1236 if( szTable )
1238 table = strdupAtoW( szTable );
1239 if( !table )
1240 goto end;
1243 if( szFolder )
1245 path = strdupAtoW( szFolder );
1246 if( !path )
1247 goto end;
1250 if( szFilename )
1252 file = strdupAtoW( szFilename );
1253 if( !file )
1254 goto end;
1257 r = MsiDatabaseExportW( handle, table, path, file );
1259 end:
1260 msi_free( table );
1261 msi_free( path );
1262 msi_free( file );
1264 return r;
1267 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1268 LPCSTR szTableName)
1270 UINT r;
1271 LPWSTR table;
1273 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1274 debugstr_a(szTableName));
1276 table = strdupAtoW(szTableName);
1277 r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1279 msi_free(table);
1280 return r;
1283 typedef struct _tagMERGETABLE
1285 struct list entry;
1286 struct list rows;
1287 LPWSTR name;
1288 DWORD numconflicts;
1289 LPWSTR *columns;
1290 DWORD numcolumns;
1291 LPWSTR *types;
1292 DWORD numtypes;
1293 LPWSTR *labels;
1294 DWORD numlabels;
1295 } MERGETABLE;
1297 typedef struct _tagMERGEROW
1299 struct list entry;
1300 MSIRECORD *data;
1301 } MERGEROW;
1303 typedef struct _tagMERGEDATA
1305 MSIDATABASE *db;
1306 MSIDATABASE *merge;
1307 MERGETABLE *curtable;
1308 MSIQUERY *curview;
1309 struct list *tabledata;
1310 } MERGEDATA;
1312 static BOOL merge_type_match(LPCWSTR type1, LPCWSTR type2)
1314 if (((type1[0] == 'l') || (type1[0] == 's')) &&
1315 ((type2[0] == 'l') || (type2[0] == 's')))
1316 return TRUE;
1318 if (((type1[0] == 'L') || (type1[0] == 'S')) &&
1319 ((type2[0] == 'L') || (type2[0] == 'S')))
1320 return TRUE;
1322 return !lstrcmpW(type1, type2);
1325 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1327 MSIRECORD *dbrec, *mergerec;
1328 UINT r, i, count;
1330 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1331 if (r != ERROR_SUCCESS)
1332 return r;
1334 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1335 if (r != ERROR_SUCCESS)
1336 return r;
1338 count = MSI_RecordGetFieldCount(dbrec);
1339 for (i = 1; i <= count; i++)
1341 if (!MSI_RecordGetString(mergerec, i))
1342 break;
1344 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1345 MSI_RecordGetString(mergerec, i)))
1347 r = ERROR_DATATYPE_MISMATCH;
1348 goto done;
1352 msiobj_release(&dbrec->hdr);
1353 msiobj_release(&mergerec->hdr);
1354 dbrec = mergerec = NULL;
1356 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_TYPES, &dbrec);
1357 if (r != ERROR_SUCCESS)
1358 return r;
1360 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1361 if (r != ERROR_SUCCESS)
1362 return r;
1364 count = MSI_RecordGetFieldCount(dbrec);
1365 for (i = 1; i <= count; i++)
1367 if (!MSI_RecordGetString(mergerec, i))
1368 break;
1370 if (!merge_type_match(MSI_RecordGetString(dbrec, i),
1371 MSI_RecordGetString(mergerec, i)))
1373 r = ERROR_DATATYPE_MISMATCH;
1374 break;
1378 done:
1379 msiobj_release(&dbrec->hdr);
1380 msiobj_release(&mergerec->hdr);
1382 return r;
1385 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1386 LPCWSTR table)
1388 MSIRECORD *dbrec, *mergerec = NULL;
1389 UINT r, i, count;
1391 r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1392 if (r != ERROR_SUCCESS)
1393 return r;
1395 r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1396 if (r != ERROR_SUCCESS)
1397 goto done;
1399 count = MSI_RecordGetFieldCount(dbrec);
1400 if (count != MSI_RecordGetFieldCount(mergerec))
1402 r = ERROR_DATATYPE_MISMATCH;
1403 goto done;
1406 for (i = 1; i <= count; i++)
1408 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1409 MSI_RecordGetString(mergerec, i)))
1411 r = ERROR_DATATYPE_MISMATCH;
1412 goto done;
1416 done:
1417 msiobj_release(&dbrec->hdr);
1418 msiobj_release(&mergerec->hdr);
1420 return r;
1423 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1425 MSIRECORD *colnames;
1426 LPWSTR str, val;
1427 UINT r, i = 0, sz = 0;
1428 int cmp;
1430 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1431 if (r != ERROR_SUCCESS)
1432 return NULL;
1436 str = msi_dup_record_field(colnames, ++i);
1437 cmp = lstrcmpW(key, str);
1438 msi_free(str);
1439 } while (cmp);
1441 msiobj_release(&colnames->hdr);
1443 r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1444 if (r != ERROR_SUCCESS)
1445 return NULL;
1446 sz++;
1448 if (MSI_RecordGetString(rec, i)) /* check record field is a string */
1450 /* quote string record fields */
1451 const WCHAR szQuote[] = {'\'', 0};
1452 sz += 2;
1453 val = msi_alloc(sz*sizeof(WCHAR));
1454 if (!val)
1455 return NULL;
1457 lstrcpyW(val, szQuote);
1458 r = MSI_RecordGetStringW(rec, i, val+1, &sz);
1459 lstrcpyW(val+1+sz, szQuote);
1461 else
1463 /* do not quote integer record fields */
1464 val = msi_alloc(sz*sizeof(WCHAR));
1465 if (!val)
1466 return NULL;
1468 r = MSI_RecordGetStringW(rec, i, val, &sz);
1471 if (r != ERROR_SUCCESS)
1473 ERR("failed to get string!\n");
1474 msi_free(val);
1475 return NULL;
1478 return val;
1481 static LPWSTR create_diff_row_query(MSIDATABASE *merge, MSIQUERY *view,
1482 LPWSTR table, MSIRECORD *rec)
1484 LPWSTR query = NULL, clause = NULL;
1485 LPWSTR ptr = NULL, val;
1486 LPCWSTR setptr;
1487 DWORD size = 1, oldsize;
1488 LPCWSTR key;
1489 MSIRECORD *keys;
1490 UINT r, i, count;
1492 static const WCHAR keyset[] = {
1493 '`','%','s','`',' ','=',' ','%','s',' ','A','N','D',' ',0};
1494 static const WCHAR lastkeyset[] = {
1495 '`','%','s','`',' ','=',' ','%','s',' ',0};
1496 static const WCHAR fmt[] = {'S','E','L','E','C','T',' ','*',' ',
1497 'F','R','O','M',' ','`','%','s','`',' ',
1498 'W','H','E','R','E',' ','%','s',0};
1500 r = MSI_DatabaseGetPrimaryKeys(merge, table, &keys);
1501 if (r != ERROR_SUCCESS)
1502 return NULL;
1504 clause = msi_alloc_zero(size * sizeof(WCHAR));
1505 if (!clause)
1506 goto done;
1508 ptr = clause;
1509 count = MSI_RecordGetFieldCount(keys);
1510 for (i = 1; i <= count; i++)
1512 key = MSI_RecordGetString(keys, i);
1513 val = get_key_value(view, key, rec);
1515 if (i == count)
1516 setptr = lastkeyset;
1517 else
1518 setptr = keyset;
1520 oldsize = size;
1521 size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1522 clause = msi_realloc(clause, size * sizeof (WCHAR));
1523 if (!clause)
1525 msi_free(val);
1526 goto done;
1529 ptr = clause + oldsize - 1;
1530 sprintfW(ptr, setptr, key, val);
1531 msi_free(val);
1534 size = lstrlenW(fmt) + lstrlenW(table) + lstrlenW(clause) + 1;
1535 query = msi_alloc(size * sizeof(WCHAR));
1536 if (!query)
1537 goto done;
1539 sprintfW(query, fmt, table, clause);
1541 done:
1542 msi_free(clause);
1543 msiobj_release(&keys->hdr);
1544 return query;
1547 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1549 MERGEDATA *data = param;
1550 MERGETABLE *table = data->curtable;
1551 MERGEROW *mergerow;
1552 MSIQUERY *dbview = NULL;
1553 MSIRECORD *row = NULL;
1554 LPWSTR query = NULL;
1555 UINT r = ERROR_SUCCESS;
1557 if (TABLE_Exists(data->db, table->name))
1559 query = create_diff_row_query(data->merge, data->curview, table->name, rec);
1560 if (!query)
1561 return ERROR_OUTOFMEMORY;
1563 r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1564 if (r != ERROR_SUCCESS)
1565 goto done;
1567 r = MSI_ViewExecute(dbview, NULL);
1568 if (r != ERROR_SUCCESS)
1569 goto done;
1571 r = MSI_ViewFetch(dbview, &row);
1572 if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1574 table->numconflicts++;
1575 goto done;
1577 else if (r != ERROR_NO_MORE_ITEMS)
1578 goto done;
1580 r = ERROR_SUCCESS;
1583 mergerow = msi_alloc(sizeof(MERGEROW));
1584 if (!mergerow)
1586 r = ERROR_OUTOFMEMORY;
1587 goto done;
1590 mergerow->data = MSI_CloneRecord(rec);
1591 if (!mergerow->data)
1593 r = ERROR_OUTOFMEMORY;
1594 msi_free(mergerow);
1595 goto done;
1598 list_add_tail(&table->rows, &mergerow->entry);
1600 done:
1601 msi_free(query);
1602 msiobj_release(&row->hdr);
1603 msiobj_release(&dbview->hdr);
1604 return r;
1607 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1609 UINT r, i, count;
1610 MSIRECORD *prec = NULL;
1612 r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1613 if (r != ERROR_SUCCESS)
1614 return r;
1616 count = MSI_RecordGetFieldCount(prec);
1617 *numlabels = count + 1;
1618 *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1619 if (!*labels)
1621 r = ERROR_OUTOFMEMORY;
1622 goto end;
1625 (*labels)[0] = strdupW(table);
1626 for (i=1; i<=count; i++ )
1628 (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1631 end:
1632 msiobj_release( &prec->hdr );
1633 return r;
1636 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1638 UINT r, i, count;
1639 MSIRECORD *prec = NULL;
1641 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1642 if (r != ERROR_SUCCESS)
1643 return r;
1645 count = MSI_RecordGetFieldCount(prec);
1646 *columns = msi_alloc(count*sizeof(LPWSTR));
1647 if (!*columns)
1649 r = ERROR_OUTOFMEMORY;
1650 goto end;
1653 for (i=1; i<=count; i++ )
1655 (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1658 *numcolumns = count;
1660 end:
1661 msiobj_release( &prec->hdr );
1662 return r;
1665 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1667 UINT r, i, count;
1668 MSIRECORD *prec = NULL;
1670 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1671 if (r != ERROR_SUCCESS)
1672 return r;
1674 count = MSI_RecordGetFieldCount(prec);
1675 *types = msi_alloc(count*sizeof(LPWSTR));
1676 if (!*types)
1678 r = ERROR_OUTOFMEMORY;
1679 goto end;
1682 *numtypes = count;
1683 for (i=1; i<=count; i++ )
1685 (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1688 end:
1689 msiobj_release( &prec->hdr );
1690 return r;
1693 static void merge_free_rows(MERGETABLE *table)
1695 struct list *item, *cursor;
1697 LIST_FOR_EACH_SAFE(item, cursor, &table->rows)
1699 MERGEROW *row = LIST_ENTRY(item, MERGEROW, entry);
1701 list_remove(&row->entry);
1702 msiobj_release(&row->data->hdr);
1703 msi_free(row);
1707 static void free_merge_table(MERGETABLE *table)
1709 UINT i;
1711 if (table->labels != NULL)
1713 for (i = 0; i < table->numlabels; i++)
1714 msi_free(table->labels[i]);
1716 msi_free(table->labels);
1719 if (table->columns != NULL)
1721 for (i = 0; i < table->numcolumns; i++)
1722 msi_free(table->columns[i]);
1724 msi_free(table->columns);
1727 if (table->types != NULL)
1729 for (i = 0; i < table->numtypes; i++)
1730 msi_free(table->types[i]);
1732 msi_free(table->types);
1735 msi_free(table->name);
1736 merge_free_rows(table);
1738 msi_free(table);
1741 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1743 UINT r;
1744 MERGETABLE *table;
1745 MSIQUERY *mergeview = NULL;
1747 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1748 'F','R','O','M',' ','`','%','s','`',0};
1750 table = msi_alloc_zero(sizeof(MERGETABLE));
1751 if (!table)
1753 *ptable = NULL;
1754 return ERROR_OUTOFMEMORY;
1757 r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1758 if (r != ERROR_SUCCESS)
1759 goto err;
1761 r = MSI_OpenQuery(db, &mergeview, query, name);
1762 if (r != ERROR_SUCCESS)
1763 goto err;
1765 r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1766 if (r != ERROR_SUCCESS)
1767 goto err;
1769 r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1770 if (r != ERROR_SUCCESS)
1771 goto err;
1773 list_init(&table->rows);
1775 table->name = strdupW(name);
1776 table->numconflicts = 0;
1778 msiobj_release(&mergeview->hdr);
1779 *ptable = table;
1780 return ERROR_SUCCESS;
1782 err:
1783 msiobj_release(&mergeview->hdr);
1784 free_merge_table(table);
1785 *ptable = NULL;
1786 return r;
1789 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1791 MERGEDATA *data = param;
1792 MERGETABLE *table;
1793 MSIQUERY *dbview = NULL;
1794 MSIQUERY *mergeview = NULL;
1795 LPCWSTR name;
1796 UINT r;
1798 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1799 'F','R','O','M',' ','`','%','s','`',0};
1801 name = MSI_RecordGetString(rec, 1);
1803 r = MSI_OpenQuery(data->merge, &mergeview, query, name);
1804 if (r != ERROR_SUCCESS)
1805 goto done;
1807 if (TABLE_Exists(data->db, name))
1809 r = MSI_OpenQuery(data->db, &dbview, query, name);
1810 if (r != ERROR_SUCCESS)
1811 goto done;
1813 r = merge_verify_colnames(dbview, mergeview);
1814 if (r != ERROR_SUCCESS)
1815 goto done;
1817 r = merge_verify_primary_keys(data->db, data->merge, name);
1818 if (r != ERROR_SUCCESS)
1819 goto done;
1822 r = msi_get_merge_table(data->merge, name, &table);
1823 if (r != ERROR_SUCCESS)
1824 goto done;
1826 data->curtable = table;
1827 data->curview = mergeview;
1828 r = MSI_IterateRecords(mergeview, NULL, merge_diff_row, data);
1829 if (r != ERROR_SUCCESS)
1831 free_merge_table(table);
1832 goto done;
1835 list_add_tail(data->tabledata, &table->entry);
1837 done:
1838 msiobj_release(&dbview->hdr);
1839 msiobj_release(&mergeview->hdr);
1840 return r;
1843 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1844 struct list *tabledata)
1846 UINT r;
1847 MSIQUERY *view;
1848 MERGEDATA data;
1850 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1851 'F','R','O','M',' ','`','_','T','a','b','l','e','s','`',0};
1853 r = MSI_DatabaseOpenViewW(merge, query, &view);
1854 if (r != ERROR_SUCCESS)
1855 return r;
1857 data.db = db;
1858 data.merge = merge;
1859 data.tabledata = tabledata;
1860 r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1862 msiobj_release(&view->hdr);
1863 return r;
1866 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1868 UINT r;
1869 MERGEROW *row;
1870 MSIVIEW *tv;
1872 if (!TABLE_Exists(db, table->name))
1874 r = msi_add_table_to_db(db, table->columns, table->types,
1875 table->labels, table->numlabels, table->numcolumns);
1876 if (r != ERROR_SUCCESS)
1877 return ERROR_FUNCTION_FAILED;
1880 LIST_FOR_EACH_ENTRY(row, &table->rows, MERGEROW, entry)
1882 r = TABLE_CreateView(db, table->name, &tv);
1883 if (r != ERROR_SUCCESS)
1884 return r;
1886 r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1887 tv->ops->delete(tv);
1889 if (r != ERROR_SUCCESS)
1890 return r;
1893 return ERROR_SUCCESS;
1896 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1897 LPWSTR table, DWORD numconflicts)
1899 UINT r;
1900 MSIQUERY *view;
1902 static const WCHAR create[] = {
1903 'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
1904 '`','%','s','`',' ','(','`','T','a','b','l','e','`',' ',
1905 'C','H','A','R','(','2','5','5',')',' ','N','O','T',' ',
1906 'N','U','L','L',',',' ','`','N','u','m','R','o','w','M','e','r','g','e',
1907 'C','o','n','f','l','i','c','t','s','`',' ','S','H','O','R','T',' ',
1908 'N','O','T',' ','N','U','L','L',' ','P','R','I','M','A','R','Y',' ',
1909 'K','E','Y',' ','`','T','a','b','l','e','`',')',0};
1910 static const WCHAR insert[] = {
1911 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1912 '`','%','s','`',' ','(','`','T','a','b','l','e','`',',',' ',
1913 '`','N','u','m','R','o','w','M','e','r','g','e',
1914 'C','o','n','f','l','i','c','t','s','`',')',' ','V','A','L','U','E','S',
1915 ' ','(','\'','%','s','\'',',',' ','%','d',')',0};
1917 if (!TABLE_Exists(db, error))
1919 r = MSI_OpenQuery(db, &view, create, error);
1920 if (r != ERROR_SUCCESS)
1921 return r;
1923 r = MSI_ViewExecute(view, NULL);
1924 msiobj_release(&view->hdr);
1925 if (r != ERROR_SUCCESS)
1926 return r;
1929 r = MSI_OpenQuery(db, &view, insert, error, table, numconflicts);
1930 if (r != ERROR_SUCCESS)
1931 return r;
1933 r = MSI_ViewExecute(view, NULL);
1934 msiobj_release(&view->hdr);
1935 return r;
1938 UINT WINAPI MsiDatabaseMergeW(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1939 LPCWSTR szTableName)
1941 struct list tabledata = LIST_INIT(tabledata);
1942 struct list *item, *cursor;
1943 MSIDATABASE *db, *merge;
1944 MERGETABLE *table;
1945 BOOL conflicts;
1946 UINT r;
1948 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1949 debugstr_w(szTableName));
1951 if (szTableName && !*szTableName)
1952 return ERROR_INVALID_TABLE;
1954 db = msihandle2msiinfo(hDatabase, MSIHANDLETYPE_DATABASE);
1955 merge = msihandle2msiinfo(hDatabaseMerge, MSIHANDLETYPE_DATABASE);
1956 if (!db || !merge)
1958 r = ERROR_INVALID_HANDLE;
1959 goto done;
1962 r = gather_merge_data(db, merge, &tabledata);
1963 if (r != ERROR_SUCCESS)
1964 goto done;
1966 conflicts = FALSE;
1967 LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
1969 if (table->numconflicts)
1971 conflicts = TRUE;
1973 r = update_merge_errors(db, szTableName, table->name,
1974 table->numconflicts);
1975 if (r != ERROR_SUCCESS)
1976 break;
1978 else
1980 r = merge_table(db, table);
1981 if (r != ERROR_SUCCESS)
1982 break;
1986 LIST_FOR_EACH_SAFE(item, cursor, &tabledata)
1988 MERGETABLE *table = LIST_ENTRY(item, MERGETABLE, entry);
1989 list_remove(&table->entry);
1990 free_merge_table(table);
1993 if (conflicts)
1994 r = ERROR_FUNCTION_FAILED;
1996 done:
1997 msiobj_release(&db->hdr);
1998 msiobj_release(&merge->hdr);
1999 return r;
2002 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
2004 MSIDBSTATE ret = MSIDBSTATE_READ;
2005 MSIDATABASE *db;
2007 TRACE("%d\n", handle);
2009 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
2010 if( !db )
2012 IWineMsiRemoteDatabase *remote_database;
2014 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
2015 if ( !remote_database )
2016 return MSIDBSTATE_ERROR;
2018 IWineMsiRemoteDatabase_Release( remote_database );
2019 WARN("MsiGetDatabaseState not allowed during a custom action!\n");
2021 return MSIDBSTATE_READ;
2024 if (db->mode != MSIDBOPEN_READONLY )
2025 ret = MSIDBSTATE_WRITE;
2026 msiobj_release( &db->hdr );
2028 return ret;
2031 typedef struct _msi_remote_database_impl {
2032 const IWineMsiRemoteDatabaseVtbl *lpVtbl;
2033 MSIHANDLE database;
2034 LONG refs;
2035 } msi_remote_database_impl;
2037 static inline msi_remote_database_impl* mrd_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase* iface )
2039 return (msi_remote_database_impl *)iface;
2042 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
2043 REFIID riid,LPVOID *ppobj)
2045 if( IsEqualCLSID( riid, &IID_IUnknown ) ||
2046 IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
2048 IUnknown_AddRef( iface );
2049 *ppobj = iface;
2050 return S_OK;
2053 return E_NOINTERFACE;
2056 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
2058 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
2060 return InterlockedIncrement( &This->refs );
2063 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
2065 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
2066 ULONG r;
2068 r = InterlockedDecrement( &This->refs );
2069 if (r == 0)
2071 MsiCloseHandle( This->database );
2072 msi_free( This );
2074 return r;
2077 static HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
2078 LPCWSTR table, MSICONDITION *persistent )
2080 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2081 *persistent = MsiDatabaseIsTablePersistentW(This->database, table);
2082 return S_OK;
2085 static HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
2086 LPCWSTR table, MSIHANDLE *keys )
2088 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2089 UINT r = MsiDatabaseGetPrimaryKeysW(This->database, table, keys);
2090 return HRESULT_FROM_WIN32(r);
2093 static HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
2094 UINT updatecount, MSIHANDLE *suminfo )
2096 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2097 UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
2098 return HRESULT_FROM_WIN32(r);
2101 static HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
2102 LPCWSTR query, MSIHANDLE *view )
2104 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
2105 UINT r = MsiDatabaseOpenViewW(This->database, query, view);
2106 return HRESULT_FROM_WIN32(r);
2109 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
2111 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
2112 This->database = handle;
2113 return S_OK;
2116 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
2118 mrd_QueryInterface,
2119 mrd_AddRef,
2120 mrd_Release,
2121 mrd_IsTablePersistent,
2122 mrd_GetPrimaryKeys,
2123 mrd_GetSummaryInformation,
2124 mrd_OpenView,
2125 mrd_SetMsiHandle,
2128 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
2130 msi_remote_database_impl *This;
2132 This = msi_alloc( sizeof *This );
2133 if (!This)
2134 return E_OUTOFMEMORY;
2136 This->lpVtbl = &msi_remote_database_vtbl;
2137 This->database = 0;
2138 This->refs = 1;
2140 *ppObj = This;
2142 return S_OK;