msi: Clone the open stream instead of trying to open a stream again.
[wine/hacks.git] / dlls / msi / database.c
blobb485b2115e51ae3257dfdba8657cca0406eaf26d
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 static VOID MSI_CloseDatabase( MSIOBJECTHDR *arg )
56 MSIDATABASE *db = (MSIDATABASE *) arg;
58 msi_free(db->path);
59 free_cached_tables( db );
60 msi_free_transforms( db );
61 msi_destroy_stringtable( db->strings );
62 IStorage_Release( db->storage );
63 if (db->deletefile)
65 DeleteFileW( db->deletefile );
66 msi_free( db->deletefile );
68 if (db->localfile)
70 DeleteFileW( db->localfile );
71 msi_free( db->localfile );
75 UINT MSI_OpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIDATABASE **pdb)
77 IStorage *stg = NULL;
78 HRESULT r;
79 MSIDATABASE *db = NULL;
80 UINT ret = ERROR_FUNCTION_FAILED;
81 LPCWSTR szMode, save_path;
82 STATSTG stat;
83 BOOL created = FALSE;
84 WCHAR path[MAX_PATH];
86 static const WCHAR szTables[] = { '_','T','a','b','l','e','s',0 };
88 TRACE("%s %s\n",debugstr_w(szDBPath),debugstr_w(szPersist) );
90 if( !pdb )
91 return ERROR_INVALID_PARAMETER;
93 if (szPersist - MSIDBOPEN_PATCHFILE >= MSIDBOPEN_READONLY &&
94 szPersist - MSIDBOPEN_PATCHFILE <= MSIDBOPEN_CREATEDIRECT)
96 TRACE("Database is a patch\n");
97 szPersist -= MSIDBOPEN_PATCHFILE;
100 save_path = szDBPath;
101 szMode = szPersist;
102 if( HIWORD( szPersist ) )
104 if (!CopyFileW( szDBPath, szPersist, FALSE ))
105 return ERROR_OPEN_FAILED;
107 szDBPath = szPersist;
108 szPersist = MSIDBOPEN_TRANSACT;
109 created = TRUE;
112 if( szPersist == MSIDBOPEN_READONLY )
114 r = StgOpenStorage( szDBPath, NULL,
115 STGM_DIRECT|STGM_READ|STGM_SHARE_DENY_WRITE, NULL, 0, &stg);
117 else if( szPersist == MSIDBOPEN_CREATE || szPersist == MSIDBOPEN_CREATEDIRECT )
119 /* FIXME: MSIDBOPEN_CREATE should case STGM_TRANSACTED flag to be
120 * used here: */
121 r = StgCreateDocfile( szDBPath,
122 STGM_CREATE|STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, 0, &stg);
123 if( r == ERROR_SUCCESS )
125 IStorage_SetClass( stg, &CLSID_MsiDatabase );
126 /* create the _Tables stream */
127 r = write_stream_data(stg, szTables, NULL, 0, TRUE);
128 if (SUCCEEDED(r))
129 r = msi_init_string_table( stg );
131 created = TRUE;
133 else if( szPersist == MSIDBOPEN_TRANSACT )
135 /* FIXME: MSIDBOPEN_TRANSACT should case STGM_TRANSACTED flag to be
136 * used here: */
137 r = StgOpenStorage( szDBPath, NULL,
138 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
140 else if( szPersist == MSIDBOPEN_DIRECT )
142 r = StgOpenStorage( szDBPath, NULL,
143 STGM_DIRECT|STGM_READWRITE|STGM_SHARE_EXCLUSIVE, NULL, 0, &stg);
145 else
147 ERR("unknown flag %p\n",szPersist);
148 return ERROR_INVALID_PARAMETER;
151 if( FAILED( r ) || !stg )
153 FIXME("open failed r = %08x for %s\n", r, debugstr_w(szDBPath));
154 return ERROR_FUNCTION_FAILED;
157 r = IStorage_Stat( stg, &stat, STATFLAG_NONAME );
158 if( FAILED( r ) )
160 FIXME("Failed to stat storage\n");
161 goto end;
164 if ( !IsEqualGUID( &stat.clsid, &CLSID_MsiDatabase ) &&
165 !IsEqualGUID( &stat.clsid, &CLSID_MsiPatch ) &&
166 !IsEqualGUID( &stat.clsid, &CLSID_MsiTransform ) )
168 ERR("storage GUID is not a MSI database GUID %s\n",
169 debugstr_guid(&stat.clsid) );
170 goto end;
173 db = alloc_msiobject( MSIHANDLETYPE_DATABASE, sizeof (MSIDATABASE),
174 MSI_CloseDatabase );
175 if( !db )
177 FIXME("Failed to allocate a handle\n");
178 goto end;
181 if (!strchrW( save_path, '\\' ))
183 GetCurrentDirectoryW( MAX_PATH, path );
184 lstrcatW( path, szBackSlash );
185 lstrcatW( path, save_path );
187 else
188 lstrcpyW( path, save_path );
190 db->path = strdupW( path );
192 if( TRACE_ON( msi ) )
193 enum_stream_names( stg );
195 db->storage = stg;
196 db->mode = szMode;
197 if (created)
198 db->deletefile = strdupW( szDBPath );
199 list_init( &db->tables );
200 list_init( &db->transforms );
201 list_init( &db->streams );
203 db->strings = msi_load_string_table( stg, &db->bytes_per_strref );
204 if( !db->strings )
205 goto end;
207 ret = ERROR_SUCCESS;
209 msiobj_addref( &db->hdr );
210 IStorage_AddRef( stg );
211 *pdb = db;
213 end:
214 if( db )
215 msiobj_release( &db->hdr );
216 if( stg )
217 IStorage_Release( stg );
219 return ret;
222 UINT WINAPI MsiOpenDatabaseW(LPCWSTR szDBPath, LPCWSTR szPersist, MSIHANDLE *phDB)
224 MSIDATABASE *db;
225 UINT ret;
227 TRACE("%s %s %p\n",debugstr_w(szDBPath),debugstr_w(szPersist), phDB);
229 ret = MSI_OpenDatabaseW( szDBPath, szPersist, &db );
230 if( ret == ERROR_SUCCESS )
232 *phDB = alloc_msihandle( &db->hdr );
233 if (! *phDB)
234 ret = ERROR_NOT_ENOUGH_MEMORY;
235 msiobj_release( &db->hdr );
238 return ret;
241 UINT WINAPI MsiOpenDatabaseA(LPCSTR szDBPath, LPCSTR szPersist, MSIHANDLE *phDB)
243 HRESULT r = ERROR_FUNCTION_FAILED;
244 LPWSTR szwDBPath = NULL, szwPersist = NULL;
246 TRACE("%s %s %p\n", debugstr_a(szDBPath), debugstr_a(szPersist), phDB);
248 if( szDBPath )
250 szwDBPath = strdupAtoW( szDBPath );
251 if( !szwDBPath )
252 goto end;
255 if( HIWORD(szPersist) )
257 szwPersist = strdupAtoW( szPersist );
258 if( !szwPersist )
259 goto end;
261 else
262 szwPersist = (LPWSTR)(DWORD_PTR)szPersist;
264 r = MsiOpenDatabaseW( szwDBPath, szwPersist, phDB );
266 end:
267 if( HIWORD(szPersist) )
268 msi_free( szwPersist );
269 msi_free( szwDBPath );
271 return r;
274 static LPWSTR msi_read_text_archive(LPCWSTR path)
276 HANDLE file;
277 LPSTR data = NULL;
278 LPWSTR wdata = NULL;
279 DWORD read, size = 0;
281 file = CreateFileW( path, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL );
282 if (file == INVALID_HANDLE_VALUE)
283 return NULL;
285 size = GetFileSize( file, NULL );
286 data = msi_alloc( size + 1 );
287 if (!data)
288 goto done;
290 if (!ReadFile( file, data, size, &read, NULL ))
291 goto done;
293 data[size] = '\0';
294 wdata = strdupAtoW( data );
296 done:
297 CloseHandle( file );
298 msi_free( data );
299 return wdata;
302 static void msi_parse_line(LPWSTR *line, LPWSTR **entries, DWORD *num_entries)
304 LPWSTR ptr = *line, save;
305 DWORD i, count = 1;
307 *entries = NULL;
309 /* stay on this line */
310 while (*ptr && *ptr != '\n')
312 /* entries are separated by tabs */
313 if (*ptr == '\t')
314 count++;
316 ptr++;
319 *entries = msi_alloc(count * sizeof(LPWSTR));
320 if (!*entries)
321 return;
323 /* store pointers into the data */
324 for (i = 0, ptr = *line; i < count; i++)
326 while (*ptr && *ptr == '\r') ptr++;
327 save = ptr;
329 while (*ptr && *ptr != '\t' && *ptr != '\n' && *ptr != '\r') ptr++;
331 /* NULL-separate the data */
332 if (*ptr == '\n' || *ptr == '\r')
334 while (*ptr == '\n' || *ptr == '\r')
335 *(ptr++) = '\0';
337 else if (*ptr)
338 *ptr++ = '\0';
340 (*entries)[i] = save;
343 /* move to the next line if there's more, else EOF */
344 *line = ptr;
346 if (num_entries)
347 *num_entries = count;
350 static LPWSTR msi_build_createsql_prelude(LPWSTR table)
352 LPWSTR prelude;
353 DWORD size;
355 static const WCHAR create_fmt[] = {'C','R','E','A','T','E',' ','T','A','B','L','E',' ','`','%','s','`',' ','(',' ',0};
357 size = sizeof(create_fmt)/sizeof(create_fmt[0]) + lstrlenW(table) - 2;
358 prelude = msi_alloc(size * sizeof(WCHAR));
359 if (!prelude)
360 return NULL;
362 sprintfW(prelude, create_fmt, table);
363 return prelude;
366 static LPWSTR msi_build_createsql_columns(LPWSTR *columns_data, LPWSTR *types, DWORD num_columns)
368 LPWSTR columns, p;
369 LPCWSTR type;
370 DWORD sql_size = 1, i, len;
371 WCHAR expanded[128], *ptr;
372 WCHAR size[10], comma[2], extra[30];
374 static const WCHAR column_fmt[] = {'`','%','s','`',' ','%','s','%','s','%','s','%','s',' ',0};
375 static const WCHAR size_fmt[] = {'(','%','s',')',0};
376 static const WCHAR type_char[] = {'C','H','A','R',0};
377 static const WCHAR type_int[] = {'I','N','T',0};
378 static const WCHAR type_long[] = {'L','O','N','G',0};
379 static const WCHAR type_object[] = {'O','B','J','E','C','T',0};
380 static const WCHAR type_notnull[] = {' ','N','O','T',' ','N','U','L','L',0};
381 static const WCHAR localizable[] = {' ','L','O','C','A','L','I','Z','A','B','L','E',0};
383 columns = msi_alloc_zero(sql_size * sizeof(WCHAR));
384 if (!columns)
385 return NULL;
387 for (i = 0; i < num_columns; i++)
389 type = NULL;
390 comma[1] = size[0] = extra[0] = '\0';
392 if (i == num_columns - 1)
393 comma[0] = '\0';
394 else
395 comma[0] = ',';
397 ptr = &types[i][1];
398 len = atolW(ptr);
399 extra[0] = '\0';
401 switch (types[i][0])
403 case 'l':
404 lstrcpyW(extra, type_notnull);
405 case 'L':
406 lstrcatW(extra, localizable);
407 type = type_char;
408 sprintfW(size, size_fmt, ptr);
409 break;
410 case 's':
411 lstrcpyW(extra, type_notnull);
412 case 'S':
413 type = type_char;
414 sprintfW(size, size_fmt, ptr);
415 break;
416 case 'i':
417 lstrcpyW(extra, type_notnull);
418 case 'I':
419 if (len <= 2)
420 type = type_int;
421 else if (len == 4)
422 type = type_long;
423 else
425 WARN("invalid int width %u\n", len);
426 msi_free(columns);
427 return NULL;
429 break;
430 case 'v':
431 lstrcpyW(extra, type_notnull);
432 case 'V':
433 type = type_object;
434 break;
435 default:
436 ERR("Unknown type: %c\n", types[i][0]);
437 msi_free(columns);
438 return NULL;
441 sprintfW(expanded, column_fmt, columns_data[i], type, size, extra, comma);
442 sql_size += lstrlenW(expanded);
444 p = msi_realloc(columns, sql_size * sizeof(WCHAR));
445 if (!p)
447 msi_free(columns);
448 return NULL;
450 columns = p;
452 lstrcatW(columns, expanded);
455 return columns;
458 static LPWSTR msi_build_createsql_postlude(LPWSTR *primary_keys, DWORD num_keys)
460 LPWSTR postlude, keys, ptr;
461 DWORD size, key_size, i;
463 static const WCHAR key_fmt[] = {'`','%','s','`',',',' ',0};
464 static const WCHAR postlude_fmt[] = {'P','R','I','M','A','R','Y',' ','K','E','Y',' ','%','s',')',0};
466 for (i = 0, size = 1; i < num_keys; i++)
467 size += lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) - 2;
469 keys = msi_alloc(size * sizeof(WCHAR));
470 if (!keys)
471 return NULL;
473 for (i = 0, ptr = keys; i < num_keys; i++)
475 key_size = lstrlenW(key_fmt) + lstrlenW(primary_keys[i]) -2;
476 sprintfW(ptr, key_fmt, primary_keys[i]);
477 ptr += key_size;
480 /* remove final ', ' */
481 *(ptr - 2) = '\0';
483 size = lstrlenW(postlude_fmt) + size - 1;
484 postlude = msi_alloc(size * sizeof(WCHAR));
485 if (!postlude)
486 goto done;
488 sprintfW(postlude, postlude_fmt, keys);
490 done:
491 msi_free(keys);
492 return postlude;
495 static UINT msi_add_table_to_db(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types, LPWSTR *labels, DWORD num_labels, DWORD num_columns)
497 UINT r = ERROR_OUTOFMEMORY;
498 DWORD size;
499 MSIQUERY *view;
500 LPWSTR create_sql = NULL;
501 LPWSTR prelude, columns_sql, postlude;
503 prelude = msi_build_createsql_prelude(labels[0]);
504 columns_sql = msi_build_createsql_columns(columns, types, num_columns);
505 postlude = msi_build_createsql_postlude(labels + 1, num_labels - 1); /* skip over table name */
507 if (!prelude || !columns_sql || !postlude)
508 goto done;
510 size = lstrlenW(prelude) + lstrlenW(columns_sql) + lstrlenW(postlude) + 1;
511 create_sql = msi_alloc(size * sizeof(WCHAR));
512 if (!create_sql)
513 goto done;
515 lstrcpyW(create_sql, prelude);
516 lstrcatW(create_sql, columns_sql);
517 lstrcatW(create_sql, postlude);
519 r = MSI_DatabaseOpenViewW( db, create_sql, &view );
520 if (r != ERROR_SUCCESS)
521 goto done;
523 r = MSI_ViewExecute(view, NULL);
524 MSI_ViewClose(view);
525 msiobj_release(&view->hdr);
527 done:
528 msi_free(prelude);
529 msi_free(columns_sql);
530 msi_free(postlude);
531 msi_free(create_sql);
532 return r;
535 static LPWSTR msi_import_stream_filename(LPCWSTR path, LPCWSTR name)
537 DWORD len;
538 LPWSTR fullname, ptr;
540 len = lstrlenW(path) + lstrlenW(name) + 1;
541 fullname = msi_alloc(len*sizeof(WCHAR));
542 if (!fullname)
543 return NULL;
545 lstrcpyW( fullname, path );
547 /* chop off extension from path */
548 ptr = strrchrW(fullname, '.');
549 if (!ptr)
551 msi_free (fullname);
552 return NULL;
554 *ptr++ = '\\';
555 lstrcpyW( ptr, name );
556 return fullname;
559 static UINT construct_record(DWORD num_columns, LPWSTR *types,
560 LPWSTR *data, LPWSTR path, MSIRECORD **rec)
562 UINT i;
564 *rec = MSI_CreateRecord(num_columns);
565 if (!*rec)
566 return ERROR_OUTOFMEMORY;
568 for (i = 0; i < num_columns; i++)
570 switch (types[i][0])
572 case 'L': case 'l': case 'S': case 's':
573 MSI_RecordSetStringW(*rec, i + 1, data[i]);
574 break;
575 case 'I': case 'i':
576 if (*data[i])
577 MSI_RecordSetInteger(*rec, i + 1, atoiW(data[i]));
578 break;
579 case 'V': case 'v':
580 if (*data[i])
582 UINT r;
583 LPWSTR file = msi_import_stream_filename(path, data[i]);
584 if (!file)
585 return ERROR_FUNCTION_FAILED;
587 r = MSI_RecordSetStreamFromFileW(*rec, i + 1, file);
588 msi_free (file);
589 if (r != ERROR_SUCCESS)
590 return ERROR_FUNCTION_FAILED;
592 break;
593 default:
594 ERR("Unhandled column type: %c\n", types[i][0]);
595 msiobj_release(&(*rec)->hdr);
596 return ERROR_FUNCTION_FAILED;
600 return ERROR_SUCCESS;
603 static UINT msi_add_records_to_table(MSIDATABASE *db, LPWSTR *columns, LPWSTR *types,
604 LPWSTR *labels, LPWSTR **records,
605 int num_columns, int num_records,
606 LPWSTR path)
608 UINT r;
609 int i;
610 MSIQUERY *view;
611 MSIRECORD *rec;
613 static const WCHAR select[] = {
614 'S','E','L','E','C','T',' ','*',' ',
615 'F','R','O','M',' ','`','%','s','`',0
618 r = MSI_OpenQuery(db, &view, select, labels[0]);
619 if (r != ERROR_SUCCESS)
620 return r;
622 while (MSI_ViewFetch(view, &rec) != ERROR_NO_MORE_ITEMS)
624 r = MSI_ViewModify(view, MSIMODIFY_DELETE, rec);
625 msiobj_release(&rec->hdr);
626 if (r != ERROR_SUCCESS)
627 goto done;
630 for (i = 0; i < num_records; i++)
632 r = construct_record(num_columns, types, records[i], path, &rec);
633 if (r != ERROR_SUCCESS)
634 goto done;
636 r = MSI_ViewModify(view, MSIMODIFY_INSERT, rec);
637 if (r != ERROR_SUCCESS)
639 msiobj_release(&rec->hdr);
640 goto done;
643 msiobj_release(&rec->hdr);
646 done:
647 msiobj_release(&view->hdr);
648 return r;
651 static UINT MSI_DatabaseImport(MSIDATABASE *db, LPCWSTR folder, LPCWSTR file)
653 UINT r;
654 DWORD len, i;
655 DWORD num_labels, num_types;
656 DWORD num_columns, num_records = 0;
657 LPWSTR *columns, *types, *labels;
658 LPWSTR path, ptr, data;
659 LPWSTR **records = NULL;
660 LPWSTR **temp_records;
662 static const WCHAR suminfo[] =
663 {'_','S','u','m','m','a','r','y','I','n','f','o','r','m','a','t','i','o','n',0};
665 TRACE("%p %s %s\n", db, debugstr_w(folder), debugstr_w(file) );
667 if( folder == NULL || file == NULL )
668 return ERROR_INVALID_PARAMETER;
670 len = lstrlenW(folder) + lstrlenW(szBackSlash) + lstrlenW(file) + 1;
671 path = msi_alloc( len * sizeof(WCHAR) );
672 if (!path)
673 return ERROR_OUTOFMEMORY;
675 lstrcpyW( path, folder );
676 lstrcatW( path, szBackSlash );
677 lstrcatW( path, file );
679 data = msi_read_text_archive( path );
681 ptr = data;
682 msi_parse_line( &ptr, &columns, &num_columns );
683 msi_parse_line( &ptr, &types, &num_types );
684 msi_parse_line( &ptr, &labels, &num_labels );
686 if (num_columns != num_types)
688 r = ERROR_FUNCTION_FAILED;
689 goto done;
692 records = msi_alloc(sizeof(LPWSTR *));
693 if (!records)
695 r = ERROR_OUTOFMEMORY;
696 goto done;
699 /* read in the table records */
700 while (*ptr)
702 msi_parse_line( &ptr, &records[num_records], NULL );
704 num_records++;
705 temp_records = msi_realloc(records, (num_records + 1) * sizeof(LPWSTR *));
706 if (!temp_records)
708 r = ERROR_OUTOFMEMORY;
709 goto done;
711 records = temp_records;
714 if (!strcmpW(labels[0], suminfo))
716 r = msi_add_suminfo( db, records, num_records, num_columns );
717 if (r != ERROR_SUCCESS)
719 r = ERROR_FUNCTION_FAILED;
720 goto done;
723 else
725 if (!TABLE_Exists(db, labels[0]))
727 r = msi_add_table_to_db( db, columns, types, labels, num_labels, num_columns );
728 if (r != ERROR_SUCCESS)
730 r = ERROR_FUNCTION_FAILED;
731 goto done;
735 r = msi_add_records_to_table( db, columns, types, labels, records, num_columns, num_records, path );
738 done:
739 msi_free(path);
740 msi_free(data);
741 msi_free(columns);
742 msi_free(types);
743 msi_free(labels);
745 for (i = 0; i < num_records; i++)
746 msi_free(records[i]);
748 msi_free(records);
750 return r;
753 UINT WINAPI MsiDatabaseImportW(MSIHANDLE handle, LPCWSTR szFolder, LPCWSTR szFilename)
755 MSIDATABASE *db;
756 UINT r;
758 TRACE("%x %s %s\n",handle,debugstr_w(szFolder), debugstr_w(szFilename));
760 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
761 if( !db )
763 IWineMsiRemoteDatabase *remote_database;
765 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
766 if ( !remote_database )
767 return ERROR_INVALID_HANDLE;
769 IWineMsiRemoteDatabase_Release( remote_database );
770 WARN("MsiDatabaseImport not allowed during a custom action!\n");
772 return ERROR_SUCCESS;
775 r = MSI_DatabaseImport( db, szFolder, szFilename );
776 msiobj_release( &db->hdr );
777 return r;
780 UINT WINAPI MsiDatabaseImportA( MSIHANDLE handle,
781 LPCSTR szFolder, LPCSTR szFilename )
783 LPWSTR path = NULL, file = NULL;
784 UINT r = ERROR_OUTOFMEMORY;
786 TRACE("%x %s %s\n", handle, debugstr_a(szFolder), debugstr_a(szFilename));
788 if( szFolder )
790 path = strdupAtoW( szFolder );
791 if( !path )
792 goto end;
795 if( szFilename )
797 file = strdupAtoW( szFilename );
798 if( !file )
799 goto end;
802 r = MsiDatabaseImportW( handle, path, file );
804 end:
805 msi_free( path );
806 msi_free( file );
808 return r;
811 static UINT msi_export_record( HANDLE handle, MSIRECORD *row, UINT start )
813 UINT i, count, len, r = ERROR_SUCCESS;
814 const char *sep;
815 char *buffer;
816 DWORD sz;
818 len = 0x100;
819 buffer = msi_alloc( len );
820 if ( !buffer )
821 return ERROR_OUTOFMEMORY;
823 count = MSI_RecordGetFieldCount( row );
824 for ( i=start; i<=count; i++ )
826 sz = len;
827 r = MSI_RecordGetStringA( row, i, buffer, &sz );
828 if (r == ERROR_MORE_DATA)
830 char *p = msi_realloc( buffer, sz + 1 );
831 if (!p)
832 break;
833 len = sz + 1;
834 buffer = p;
836 sz = len;
837 r = MSI_RecordGetStringA( row, i, buffer, &sz );
838 if (r != ERROR_SUCCESS)
839 break;
841 if (!WriteFile( handle, buffer, sz, &sz, NULL ))
843 r = ERROR_FUNCTION_FAILED;
844 break;
847 sep = (i < count) ? "\t" : "\r\n";
848 if (!WriteFile( handle, sep, strlen(sep), &sz, NULL ))
850 r = ERROR_FUNCTION_FAILED;
851 break;
854 msi_free( buffer );
855 return r;
858 static UINT msi_export_row( MSIRECORD *row, void *arg )
860 return msi_export_record( arg, row, 1 );
863 static UINT msi_export_forcecodepage( HANDLE handle )
865 DWORD sz;
867 static const char data[] = "\r\n\r\n0\t_ForceCodepage\r\n";
869 FIXME("Read the codepage from the strings table!\n");
871 sz = lstrlenA(data) + 1;
872 if (!WriteFile(handle, data, sz, &sz, NULL))
873 return ERROR_FUNCTION_FAILED;
875 return ERROR_SUCCESS;
878 static UINT MSI_DatabaseExport( MSIDATABASE *db, LPCWSTR table,
879 LPCWSTR folder, LPCWSTR file )
881 static const WCHAR query[] = {
882 's','e','l','e','c','t',' ','*',' ','f','r','o','m',' ','%','s',0 };
883 static const WCHAR forcecodepage[] = {
884 '_','F','o','r','c','e','C','o','d','e','p','a','g','e',0 };
885 MSIRECORD *rec = NULL;
886 MSIQUERY *view = NULL;
887 LPWSTR filename;
888 HANDLE handle;
889 UINT len, r;
891 TRACE("%p %s %s %s\n", db, debugstr_w(table),
892 debugstr_w(folder), debugstr_w(file) );
894 if( folder == NULL || file == NULL )
895 return ERROR_INVALID_PARAMETER;
897 len = lstrlenW(folder) + lstrlenW(file) + 2;
898 filename = msi_alloc(len * sizeof (WCHAR));
899 if (!filename)
900 return ERROR_OUTOFMEMORY;
902 lstrcpyW( filename, folder );
903 lstrcatW( filename, szBackSlash );
904 lstrcatW( filename, file );
906 handle = CreateFileW( filename, GENERIC_READ | GENERIC_WRITE, 0,
907 NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL );
908 msi_free( filename );
909 if (handle == INVALID_HANDLE_VALUE)
910 return ERROR_FUNCTION_FAILED;
912 if (!lstrcmpW( table, forcecodepage ))
914 r = msi_export_forcecodepage( handle );
915 goto done;
918 r = MSI_OpenQuery( db, &view, query, table );
919 if (r == ERROR_SUCCESS)
921 /* write out row 1, the column names */
922 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &rec);
923 if (r == ERROR_SUCCESS)
925 msi_export_record( handle, rec, 1 );
926 msiobj_release( &rec->hdr );
929 /* write out row 2, the column types */
930 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_TYPES, &rec);
931 if (r == ERROR_SUCCESS)
933 msi_export_record( handle, rec, 1 );
934 msiobj_release( &rec->hdr );
937 /* write out row 3, the table name + keys */
938 r = MSI_DatabaseGetPrimaryKeys( db, table, &rec );
939 if (r == ERROR_SUCCESS)
941 MSI_RecordSetStringW( rec, 0, table );
942 msi_export_record( handle, rec, 0 );
943 msiobj_release( &rec->hdr );
946 /* write out row 4 onwards, the data */
947 r = MSI_IterateRecords( view, 0, msi_export_row, handle );
948 msiobj_release( &view->hdr );
951 done:
952 CloseHandle( handle );
953 return r;
956 /***********************************************************************
957 * MsiExportDatabaseW [MSI.@]
959 * Writes a file containing the table data as tab separated ASCII.
961 * The format is as follows:
963 * row1 : colname1 <tab> colname2 <tab> .... colnameN <cr> <lf>
964 * row2 : coltype1 <tab> coltype2 <tab> .... coltypeN <cr> <lf>
965 * row3 : tablename <tab> key1 <tab> key2 <tab> ... keyM <cr> <lf>
967 * Followed by the data, starting at row 1 with one row per line
969 * row4 : data <tab> data <tab> data <tab> ... data <cr> <lf>
971 UINT WINAPI MsiDatabaseExportW( MSIHANDLE handle, LPCWSTR szTable,
972 LPCWSTR szFolder, LPCWSTR szFilename )
974 MSIDATABASE *db;
975 UINT r;
977 TRACE("%x %s %s %s\n", handle, debugstr_w(szTable),
978 debugstr_w(szFolder), debugstr_w(szFilename));
980 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
981 if( !db )
983 IWineMsiRemoteDatabase *remote_database;
985 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
986 if ( !remote_database )
987 return ERROR_INVALID_HANDLE;
989 IWineMsiRemoteDatabase_Release( remote_database );
990 WARN("MsiDatabaseExport not allowed during a custom action!\n");
992 return ERROR_SUCCESS;
995 r = MSI_DatabaseExport( db, szTable, szFolder, szFilename );
996 msiobj_release( &db->hdr );
997 return r;
1000 UINT WINAPI MsiDatabaseExportA( MSIHANDLE handle, LPCSTR szTable,
1001 LPCSTR szFolder, LPCSTR szFilename )
1003 LPWSTR path = NULL, file = NULL, table = NULL;
1004 UINT r = ERROR_OUTOFMEMORY;
1006 TRACE("%x %s %s %s\n", handle, debugstr_a(szTable),
1007 debugstr_a(szFolder), debugstr_a(szFilename));
1009 if( szTable )
1011 table = strdupAtoW( szTable );
1012 if( !table )
1013 goto end;
1016 if( szFolder )
1018 path = strdupAtoW( szFolder );
1019 if( !path )
1020 goto end;
1023 if( szFilename )
1025 file = strdupAtoW( szFilename );
1026 if( !file )
1027 goto end;
1030 r = MsiDatabaseExportW( handle, table, path, file );
1032 end:
1033 msi_free( table );
1034 msi_free( path );
1035 msi_free( file );
1037 return r;
1040 UINT WINAPI MsiDatabaseMergeA(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1041 LPCSTR szTableName)
1043 UINT r;
1044 LPWSTR table;
1046 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1047 debugstr_a(szTableName));
1049 table = strdupAtoW(szTableName);
1050 r = MsiDatabaseMergeW(hDatabase, hDatabaseMerge, table);
1052 msi_free(table);
1053 return r;
1056 typedef struct _tagMERGETABLE
1058 struct list entry;
1059 struct list rows;
1060 LPWSTR name;
1061 DWORD numconflicts;
1062 LPWSTR *columns;
1063 DWORD numcolumns;
1064 LPWSTR *types;
1065 DWORD numtypes;
1066 LPWSTR *labels;
1067 DWORD numlabels;
1068 } MERGETABLE;
1070 typedef struct _tagMERGEROW
1072 struct list entry;
1073 MSIRECORD *data;
1074 } MERGEROW;
1076 typedef struct _tagMERGEDATA
1078 MSIDATABASE *db;
1079 MSIDATABASE *merge;
1080 MERGETABLE *curtable;
1081 MSIQUERY *curview;
1082 struct list *tabledata;
1083 } MERGEDATA;
1085 static BOOL merge_type_match(LPCWSTR type1, LPCWSTR type2)
1087 if (((type1[0] == 'l') || (type1[0] == 's')) &&
1088 ((type2[0] == 'l') || (type2[0] == 's')))
1089 return TRUE;
1091 if (((type1[0] == 'L') || (type1[0] == 'S')) &&
1092 ((type2[0] == 'L') || (type2[0] == 'S')))
1093 return TRUE;
1095 return !lstrcmpW(type1, type2);
1098 static UINT merge_verify_colnames(MSIQUERY *dbview, MSIQUERY *mergeview)
1100 MSIRECORD *dbrec, *mergerec;
1101 UINT r, i, count;
1103 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_NAMES, &dbrec);
1104 if (r != ERROR_SUCCESS)
1105 return r;
1107 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_NAMES, &mergerec);
1108 if (r != ERROR_SUCCESS)
1109 return r;
1111 count = MSI_RecordGetFieldCount(dbrec);
1112 for (i = 1; i <= count; i++)
1114 if (!MSI_RecordGetString(mergerec, i))
1115 break;
1117 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1118 MSI_RecordGetString(mergerec, i)))
1120 r = ERROR_DATATYPE_MISMATCH;
1121 goto done;
1125 msiobj_release(&dbrec->hdr);
1126 msiobj_release(&mergerec->hdr);
1127 dbrec = mergerec = NULL;
1129 r = MSI_ViewGetColumnInfo(dbview, MSICOLINFO_TYPES, &dbrec);
1130 if (r != ERROR_SUCCESS)
1131 return r;
1133 r = MSI_ViewGetColumnInfo(mergeview, MSICOLINFO_TYPES, &mergerec);
1134 if (r != ERROR_SUCCESS)
1135 return r;
1137 count = MSI_RecordGetFieldCount(dbrec);
1138 for (i = 1; i <= count; i++)
1140 if (!MSI_RecordGetString(mergerec, i))
1141 break;
1143 if (!merge_type_match(MSI_RecordGetString(dbrec, i),
1144 MSI_RecordGetString(mergerec, i)))
1146 r = ERROR_DATATYPE_MISMATCH;
1147 break;
1151 done:
1152 msiobj_release(&dbrec->hdr);
1153 msiobj_release(&mergerec->hdr);
1155 return r;
1158 static UINT merge_verify_primary_keys(MSIDATABASE *db, MSIDATABASE *mergedb,
1159 LPCWSTR table)
1161 MSIRECORD *dbrec, *mergerec = NULL;
1162 UINT r, i, count;
1164 r = MSI_DatabaseGetPrimaryKeys(db, table, &dbrec);
1165 if (r != ERROR_SUCCESS)
1166 return r;
1168 r = MSI_DatabaseGetPrimaryKeys(mergedb, table, &mergerec);
1169 if (r != ERROR_SUCCESS)
1170 goto done;
1172 count = MSI_RecordGetFieldCount(dbrec);
1173 if (count != MSI_RecordGetFieldCount(mergerec))
1175 r = ERROR_DATATYPE_MISMATCH;
1176 goto done;
1179 for (i = 1; i <= count; i++)
1181 if (lstrcmpW(MSI_RecordGetString(dbrec, i),
1182 MSI_RecordGetString(mergerec, i)))
1184 r = ERROR_DATATYPE_MISMATCH;
1185 goto done;
1189 done:
1190 msiobj_release(&dbrec->hdr);
1191 msiobj_release(&mergerec->hdr);
1193 return r;
1196 static LPWSTR get_key_value(MSIQUERY *view, LPCWSTR key, MSIRECORD *rec)
1198 MSIRECORD *colnames;
1199 LPWSTR str, val;
1200 UINT r, i = 0, sz = 0;
1201 int cmp;
1203 r = MSI_ViewGetColumnInfo(view, MSICOLINFO_NAMES, &colnames);
1204 if (r != ERROR_SUCCESS)
1205 return NULL;
1209 str = msi_dup_record_field(colnames, ++i);
1210 cmp = lstrcmpW(key, str);
1211 msi_free(str);
1212 } while (cmp);
1214 msiobj_release(&colnames->hdr);
1216 r = MSI_RecordGetStringW(rec, i, NULL, &sz);
1217 if (r != ERROR_SUCCESS)
1218 return NULL;
1219 sz++;
1221 if (MSI_RecordGetString(rec, i)) /* check record field is a string */
1223 /* quote string record fields */
1224 const WCHAR szQuote[] = {'\'', 0};
1225 sz += 2;
1226 val = msi_alloc(sz*sizeof(WCHAR));
1227 if (!val)
1228 return NULL;
1230 lstrcpyW(val, szQuote);
1231 r = MSI_RecordGetStringW(rec, i, val+1, &sz);
1232 lstrcpyW(val+1+sz, szQuote);
1234 else
1236 /* do not quote integer record fields */
1237 val = msi_alloc(sz*sizeof(WCHAR));
1238 if (!val)
1239 return NULL;
1241 r = MSI_RecordGetStringW(rec, i, val, &sz);
1244 if (r != ERROR_SUCCESS)
1246 ERR("failed to get string!\n");
1247 msi_free(val);
1248 return NULL;
1251 return val;
1254 static LPWSTR create_diff_row_query(MSIDATABASE *merge, MSIQUERY *view,
1255 LPWSTR table, MSIRECORD *rec)
1257 LPWSTR query = NULL, clause = NULL;
1258 LPWSTR ptr = NULL, val;
1259 LPCWSTR setptr;
1260 DWORD size = 1, oldsize;
1261 LPCWSTR key;
1262 MSIRECORD *keys;
1263 UINT r, i, count;
1265 static const WCHAR keyset[] = {
1266 '`','%','s','`',' ','=',' ','%','s',' ','A','N','D',' ',0};
1267 static const WCHAR lastkeyset[] = {
1268 '`','%','s','`',' ','=',' ','%','s',' ',0};
1269 static const WCHAR fmt[] = {'S','E','L','E','C','T',' ','*',' ',
1270 'F','R','O','M',' ','`','%','s','`',' ',
1271 'W','H','E','R','E',' ','%','s',0};
1273 r = MSI_DatabaseGetPrimaryKeys(merge, table, &keys);
1274 if (r != ERROR_SUCCESS)
1275 return NULL;
1277 clause = msi_alloc_zero(size * sizeof(WCHAR));
1278 if (!clause)
1279 goto done;
1281 ptr = clause;
1282 count = MSI_RecordGetFieldCount(keys);
1283 for (i = 1; i <= count; i++)
1285 key = MSI_RecordGetString(keys, i);
1286 val = get_key_value(view, key, rec);
1288 if (i == count)
1289 setptr = lastkeyset;
1290 else
1291 setptr = keyset;
1293 oldsize = size;
1294 size += lstrlenW(setptr) + lstrlenW(key) + lstrlenW(val) - 4;
1295 clause = msi_realloc(clause, size * sizeof (WCHAR));
1296 if (!clause)
1298 msi_free(val);
1299 goto done;
1302 ptr = clause + oldsize - 1;
1303 sprintfW(ptr, setptr, key, val);
1304 msi_free(val);
1307 size = lstrlenW(fmt) + lstrlenW(table) + lstrlenW(clause) + 1;
1308 query = msi_alloc(size * sizeof(WCHAR));
1309 if (!query)
1310 goto done;
1312 sprintfW(query, fmt, table, clause);
1314 done:
1315 msi_free(clause);
1316 msiobj_release(&keys->hdr);
1317 return query;
1320 static UINT merge_diff_row(MSIRECORD *rec, LPVOID param)
1322 MERGEDATA *data = param;
1323 MERGETABLE *table = data->curtable;
1324 MERGEROW *mergerow;
1325 MSIQUERY *dbview = NULL;
1326 MSIRECORD *row = NULL;
1327 LPWSTR query = NULL;
1328 UINT r = ERROR_SUCCESS;
1330 if (TABLE_Exists(data->db, table->name))
1332 query = create_diff_row_query(data->merge, data->curview, table->name, rec);
1333 if (!query)
1334 return ERROR_OUTOFMEMORY;
1336 r = MSI_DatabaseOpenViewW(data->db, query, &dbview);
1337 if (r != ERROR_SUCCESS)
1338 goto done;
1340 r = MSI_ViewExecute(dbview, NULL);
1341 if (r != ERROR_SUCCESS)
1342 goto done;
1344 r = MSI_ViewFetch(dbview, &row);
1345 if (r == ERROR_SUCCESS && !MSI_RecordsAreEqual(rec, row))
1347 table->numconflicts++;
1348 goto done;
1350 else if (r != ERROR_NO_MORE_ITEMS)
1351 goto done;
1353 r = ERROR_SUCCESS;
1356 mergerow = msi_alloc(sizeof(MERGEROW));
1357 if (!mergerow)
1359 r = ERROR_OUTOFMEMORY;
1360 goto done;
1363 mergerow->data = MSI_CloneRecord(rec);
1364 if (!mergerow->data)
1366 r = ERROR_OUTOFMEMORY;
1367 msi_free(mergerow);
1368 goto done;
1371 list_add_tail(&table->rows, &mergerow->entry);
1373 done:
1374 msi_free(query);
1375 msiobj_release(&row->hdr);
1376 msiobj_release(&dbview->hdr);
1377 return r;
1380 static UINT msi_get_table_labels(MSIDATABASE *db, LPCWSTR table, LPWSTR **labels, DWORD *numlabels)
1382 UINT r, i, count;
1383 MSIRECORD *prec = NULL;
1385 r = MSI_DatabaseGetPrimaryKeys(db, table, &prec);
1386 if (r != ERROR_SUCCESS)
1387 return r;
1389 count = MSI_RecordGetFieldCount(prec);
1390 *numlabels = count + 1;
1391 *labels = msi_alloc((*numlabels)*sizeof(LPWSTR));
1392 if (!*labels)
1394 r = ERROR_OUTOFMEMORY;
1395 goto end;
1398 (*labels)[0] = strdupW(table);
1399 for (i=1; i<=count; i++ )
1401 (*labels)[i] = strdupW(MSI_RecordGetString(prec, i));
1404 end:
1405 msiobj_release( &prec->hdr );
1406 return r;
1409 static UINT msi_get_query_columns(MSIQUERY *query, LPWSTR **columns, DWORD *numcolumns)
1411 UINT r, i, count;
1412 MSIRECORD *prec = NULL;
1414 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_NAMES, &prec);
1415 if (r != ERROR_SUCCESS)
1416 return r;
1418 count = MSI_RecordGetFieldCount(prec);
1419 *columns = msi_alloc(count*sizeof(LPWSTR));
1420 if (!*columns)
1422 r = ERROR_OUTOFMEMORY;
1423 goto end;
1426 for (i=1; i<=count; i++ )
1428 (*columns)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1431 *numcolumns = count;
1433 end:
1434 msiobj_release( &prec->hdr );
1435 return r;
1438 static UINT msi_get_query_types(MSIQUERY *query, LPWSTR **types, DWORD *numtypes)
1440 UINT r, i, count;
1441 MSIRECORD *prec = NULL;
1443 r = MSI_ViewGetColumnInfo(query, MSICOLINFO_TYPES, &prec);
1444 if (r != ERROR_SUCCESS)
1445 return r;
1447 count = MSI_RecordGetFieldCount(prec);
1448 *types = msi_alloc(count*sizeof(LPWSTR));
1449 if (!*types)
1451 r = ERROR_OUTOFMEMORY;
1452 goto end;
1455 *numtypes = count;
1456 for (i=1; i<=count; i++ )
1458 (*types)[i-1] = strdupW(MSI_RecordGetString(prec, i));
1461 end:
1462 msiobj_release( &prec->hdr );
1463 return r;
1466 static void merge_free_rows(MERGETABLE *table)
1468 struct list *item, *cursor;
1470 LIST_FOR_EACH_SAFE(item, cursor, &table->rows)
1472 MERGEROW *row = LIST_ENTRY(item, MERGEROW, entry);
1474 list_remove(&row->entry);
1475 msiobj_release(&row->data->hdr);
1476 msi_free(row);
1480 static void free_merge_table(MERGETABLE *table)
1482 UINT i;
1484 if (table->labels != NULL)
1486 for (i = 0; i < table->numlabels; i++)
1487 msi_free(table->labels[i]);
1489 msi_free(table->labels);
1492 if (table->columns != NULL)
1494 for (i = 0; i < table->numcolumns; i++)
1495 msi_free(table->columns[i]);
1497 msi_free(table->columns);
1500 if (table->types != NULL)
1502 for (i = 0; i < table->numtypes; i++)
1503 msi_free(table->types[i]);
1505 msi_free(table->types);
1508 msi_free(table->name);
1509 merge_free_rows(table);
1511 msi_free(table);
1514 static UINT msi_get_merge_table (MSIDATABASE *db, LPCWSTR name, MERGETABLE **ptable)
1516 UINT r;
1517 MERGETABLE *table;
1518 MSIQUERY *mergeview = NULL;
1520 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1521 'F','R','O','M',' ','`','%','s','`',0};
1523 table = msi_alloc_zero(sizeof(MERGETABLE));
1524 if (!table)
1526 *ptable = NULL;
1527 return ERROR_OUTOFMEMORY;
1530 r = msi_get_table_labels(db, name, &table->labels, &table->numlabels);
1531 if (r != ERROR_SUCCESS)
1532 goto err;
1534 r = MSI_OpenQuery(db, &mergeview, query, name);
1535 if (r != ERROR_SUCCESS)
1536 goto err;
1538 r = msi_get_query_columns(mergeview, &table->columns, &table->numcolumns);
1539 if (r != ERROR_SUCCESS)
1540 goto err;
1542 r = msi_get_query_types(mergeview, &table->types, &table->numtypes);
1543 if (r != ERROR_SUCCESS)
1544 goto err;
1546 list_init(&table->rows);
1548 table->name = strdupW(name);
1549 table->numconflicts = 0;
1551 msiobj_release(&mergeview->hdr);
1552 *ptable = table;
1553 return ERROR_SUCCESS;
1555 err:
1556 msiobj_release(&mergeview->hdr);
1557 free_merge_table(table);
1558 *ptable = NULL;
1559 return r;
1562 static UINT merge_diff_tables(MSIRECORD *rec, LPVOID param)
1564 MERGEDATA *data = param;
1565 MERGETABLE *table;
1566 MSIQUERY *dbview = NULL;
1567 MSIQUERY *mergeview = NULL;
1568 LPCWSTR name;
1569 UINT r;
1571 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1572 'F','R','O','M',' ','`','%','s','`',0};
1574 name = MSI_RecordGetString(rec, 1);
1576 r = MSI_OpenQuery(data->merge, &mergeview, query, name);
1577 if (r != ERROR_SUCCESS)
1578 goto done;
1580 if (TABLE_Exists(data->db, name))
1582 r = MSI_OpenQuery(data->db, &dbview, query, name);
1583 if (r != ERROR_SUCCESS)
1584 goto done;
1586 r = merge_verify_colnames(dbview, mergeview);
1587 if (r != ERROR_SUCCESS)
1588 goto done;
1590 r = merge_verify_primary_keys(data->db, data->merge, name);
1591 if (r != ERROR_SUCCESS)
1592 goto done;
1595 r = msi_get_merge_table(data->merge, name, &table);
1596 if (r != ERROR_SUCCESS)
1597 goto done;
1599 data->curtable = table;
1600 data->curview = mergeview;
1601 r = MSI_IterateRecords(mergeview, NULL, merge_diff_row, data);
1602 if (r != ERROR_SUCCESS)
1604 free_merge_table(table);
1605 goto done;
1608 list_add_tail(data->tabledata, &table->entry);
1610 done:
1611 msiobj_release(&dbview->hdr);
1612 msiobj_release(&mergeview->hdr);
1613 return r;
1616 static UINT gather_merge_data(MSIDATABASE *db, MSIDATABASE *merge,
1617 struct list *tabledata)
1619 UINT r;
1620 MSIQUERY *view;
1621 MERGEDATA data;
1623 static const WCHAR query[] = {'S','E','L','E','C','T',' ','*',' ',
1624 'F','R','O','M',' ','`','_','T','a','b','l','e','s','`',0};
1626 r = MSI_DatabaseOpenViewW(merge, query, &view);
1627 if (r != ERROR_SUCCESS)
1628 return r;
1630 data.db = db;
1631 data.merge = merge;
1632 data.tabledata = tabledata;
1633 r = MSI_IterateRecords(view, NULL, merge_diff_tables, &data);
1635 msiobj_release(&view->hdr);
1636 return r;
1639 static UINT merge_table(MSIDATABASE *db, MERGETABLE *table)
1641 UINT r;
1642 MERGEROW *row;
1643 MSIVIEW *tv;
1645 if (!TABLE_Exists(db, table->name))
1647 r = msi_add_table_to_db(db, table->columns, table->types,
1648 table->labels, table->numlabels, table->numcolumns);
1649 if (r != ERROR_SUCCESS)
1650 return ERROR_FUNCTION_FAILED;
1653 LIST_FOR_EACH_ENTRY(row, &table->rows, MERGEROW, entry)
1655 r = TABLE_CreateView(db, table->name, &tv);
1656 if (r != ERROR_SUCCESS)
1657 return r;
1659 r = tv->ops->insert_row(tv, row->data, -1, FALSE);
1660 tv->ops->delete(tv);
1662 if (r != ERROR_SUCCESS)
1663 return r;
1666 return ERROR_SUCCESS;
1669 static UINT update_merge_errors(MSIDATABASE *db, LPCWSTR error,
1670 LPWSTR table, DWORD numconflicts)
1672 UINT r;
1673 MSIQUERY *view;
1675 static const WCHAR create[] = {
1676 'C','R','E','A','T','E',' ','T','A','B','L','E',' ',
1677 '`','%','s','`',' ','(','`','T','a','b','l','e','`',' ',
1678 'C','H','A','R','(','2','5','5',')',' ','N','O','T',' ',
1679 'N','U','L','L',',',' ','`','N','u','m','R','o','w','M','e','r','g','e',
1680 'C','o','n','f','l','i','c','t','s','`',' ','S','H','O','R','T',' ',
1681 'N','O','T',' ','N','U','L','L',' ','P','R','I','M','A','R','Y',' ',
1682 'K','E','Y',' ','`','T','a','b','l','e','`',')',0};
1683 static const WCHAR insert[] = {
1684 'I','N','S','E','R','T',' ','I','N','T','O',' ',
1685 '`','%','s','`',' ','(','`','T','a','b','l','e','`',',',' ',
1686 '`','N','u','m','R','o','w','M','e','r','g','e',
1687 'C','o','n','f','l','i','c','t','s','`',')',' ','V','A','L','U','E','S',
1688 ' ','(','\'','%','s','\'',',',' ','%','d',')',0};
1690 if (!TABLE_Exists(db, error))
1692 r = MSI_OpenQuery(db, &view, create, error);
1693 if (r != ERROR_SUCCESS)
1694 return r;
1696 r = MSI_ViewExecute(view, NULL);
1697 msiobj_release(&view->hdr);
1698 if (r != ERROR_SUCCESS)
1699 return r;
1702 r = MSI_OpenQuery(db, &view, insert, error, table, numconflicts);
1703 if (r != ERROR_SUCCESS)
1704 return r;
1706 r = MSI_ViewExecute(view, NULL);
1707 msiobj_release(&view->hdr);
1708 return r;
1711 UINT WINAPI MsiDatabaseMergeW(MSIHANDLE hDatabase, MSIHANDLE hDatabaseMerge,
1712 LPCWSTR szTableName)
1714 struct list tabledata = LIST_INIT(tabledata);
1715 struct list *item, *cursor;
1716 MSIDATABASE *db, *merge;
1717 MERGETABLE *table;
1718 BOOL conflicts;
1719 UINT r;
1721 TRACE("(%d, %d, %s)\n", hDatabase, hDatabaseMerge,
1722 debugstr_w(szTableName));
1724 if (szTableName && !*szTableName)
1725 return ERROR_INVALID_TABLE;
1727 db = msihandle2msiinfo(hDatabase, MSIHANDLETYPE_DATABASE);
1728 merge = msihandle2msiinfo(hDatabaseMerge, MSIHANDLETYPE_DATABASE);
1729 if (!db || !merge)
1731 r = ERROR_INVALID_HANDLE;
1732 goto done;
1735 r = gather_merge_data(db, merge, &tabledata);
1736 if (r != ERROR_SUCCESS)
1737 goto done;
1739 conflicts = FALSE;
1740 LIST_FOR_EACH_ENTRY(table, &tabledata, MERGETABLE, entry)
1742 if (table->numconflicts)
1744 conflicts = TRUE;
1746 r = update_merge_errors(db, szTableName, table->name,
1747 table->numconflicts);
1748 if (r != ERROR_SUCCESS)
1749 break;
1751 else
1753 r = merge_table(db, table);
1754 if (r != ERROR_SUCCESS)
1755 break;
1759 LIST_FOR_EACH_SAFE(item, cursor, &tabledata)
1761 MERGETABLE *table = LIST_ENTRY(item, MERGETABLE, entry);
1762 list_remove(&table->entry);
1763 free_merge_table(table);
1766 if (conflicts)
1767 r = ERROR_FUNCTION_FAILED;
1769 done:
1770 msiobj_release(&db->hdr);
1771 msiobj_release(&merge->hdr);
1772 return r;
1775 MSIDBSTATE WINAPI MsiGetDatabaseState( MSIHANDLE handle )
1777 MSIDBSTATE ret = MSIDBSTATE_READ;
1778 MSIDATABASE *db;
1780 TRACE("%d\n", handle);
1782 db = msihandle2msiinfo( handle, MSIHANDLETYPE_DATABASE );
1783 if( !db )
1785 IWineMsiRemoteDatabase *remote_database;
1787 remote_database = (IWineMsiRemoteDatabase *)msi_get_remote( handle );
1788 if ( !remote_database )
1789 return MSIDBSTATE_ERROR;
1791 IWineMsiRemoteDatabase_Release( remote_database );
1792 WARN("MsiGetDatabaseState not allowed during a custom action!\n");
1794 return MSIDBSTATE_READ;
1797 if (db->mode != MSIDBOPEN_READONLY )
1798 ret = MSIDBSTATE_WRITE;
1799 msiobj_release( &db->hdr );
1801 return ret;
1804 typedef struct _msi_remote_database_impl {
1805 const IWineMsiRemoteDatabaseVtbl *lpVtbl;
1806 MSIHANDLE database;
1807 LONG refs;
1808 } msi_remote_database_impl;
1810 static inline msi_remote_database_impl* mrd_from_IWineMsiRemoteDatabase( IWineMsiRemoteDatabase* iface )
1812 return (msi_remote_database_impl *)iface;
1815 static HRESULT WINAPI mrd_QueryInterface( IWineMsiRemoteDatabase *iface,
1816 REFIID riid,LPVOID *ppobj)
1818 if( IsEqualCLSID( riid, &IID_IUnknown ) ||
1819 IsEqualCLSID( riid, &IID_IWineMsiRemoteDatabase ) )
1821 IUnknown_AddRef( iface );
1822 *ppobj = iface;
1823 return S_OK;
1826 return E_NOINTERFACE;
1829 static ULONG WINAPI mrd_AddRef( IWineMsiRemoteDatabase *iface )
1831 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1833 return InterlockedIncrement( &This->refs );
1836 static ULONG WINAPI mrd_Release( IWineMsiRemoteDatabase *iface )
1838 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1839 ULONG r;
1841 r = InterlockedDecrement( &This->refs );
1842 if (r == 0)
1844 MsiCloseHandle( This->database );
1845 msi_free( This );
1847 return r;
1850 static HRESULT WINAPI mrd_IsTablePersistent( IWineMsiRemoteDatabase *iface,
1851 BSTR table, MSICONDITION *persistent )
1853 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1854 *persistent = MsiDatabaseIsTablePersistentW(This->database, table);
1855 return S_OK;
1858 static HRESULT WINAPI mrd_GetPrimaryKeys( IWineMsiRemoteDatabase *iface,
1859 BSTR table, MSIHANDLE *keys )
1861 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1862 UINT r = MsiDatabaseGetPrimaryKeysW(This->database, table, keys);
1863 return HRESULT_FROM_WIN32(r);
1866 static HRESULT WINAPI mrd_GetSummaryInformation( IWineMsiRemoteDatabase *iface,
1867 UINT updatecount, MSIHANDLE *suminfo )
1869 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1870 UINT r = MsiGetSummaryInformationW(This->database, NULL, updatecount, suminfo);
1871 return HRESULT_FROM_WIN32(r);
1874 static HRESULT WINAPI mrd_OpenView( IWineMsiRemoteDatabase *iface,
1875 BSTR query, MSIHANDLE *view )
1877 msi_remote_database_impl *This = mrd_from_IWineMsiRemoteDatabase( iface );
1878 UINT r = MsiDatabaseOpenViewW(This->database, query, view);
1879 return HRESULT_FROM_WIN32(r);
1882 static HRESULT WINAPI mrd_SetMsiHandle( IWineMsiRemoteDatabase *iface, MSIHANDLE handle )
1884 msi_remote_database_impl* This = mrd_from_IWineMsiRemoteDatabase( iface );
1885 This->database = handle;
1886 return S_OK;
1889 static const IWineMsiRemoteDatabaseVtbl msi_remote_database_vtbl =
1891 mrd_QueryInterface,
1892 mrd_AddRef,
1893 mrd_Release,
1894 mrd_IsTablePersistent,
1895 mrd_GetPrimaryKeys,
1896 mrd_GetSummaryInformation,
1897 mrd_OpenView,
1898 mrd_SetMsiHandle,
1901 HRESULT create_msi_remote_database( IUnknown *pOuter, LPVOID *ppObj )
1903 msi_remote_database_impl *This;
1905 This = msi_alloc( sizeof *This );
1906 if (!This)
1907 return E_OUTOFMEMORY;
1909 This->lpVtbl = &msi_remote_database_vtbl;
1910 This->database = 0;
1911 This->refs = 1;
1913 *ppObj = This;
1915 return S_OK;